• Welcome, Guest. Please login.
 
June 16, 2019, 10:19:16 pm

News:

Welcome to the SQLitening support forums!


Assure threads allocate example

Started by cj, July 16, 2016, 02:30:44 pm

Previous topic - Next topic

cj

July 16, 2016, 02:30:44 pm Last Edit: July 20, 2016, 03:39:15 am by cj
GLOBAL gsResult AS STRING
TYPE MyType
  sDatabase AS STRING * 64
  sIpAddress AS STRING * 32
  PortNumber AS LONG
  sql      AS STRING * 512
  hEventReady AS LONG
END TYPE

#INCLUDE ONCE "win32api.inc"
#INCLUDE ONCE "sqlitening.inc"

FUNCTION PBMAIN () AS LONG
  slSetProcessMods "E0" 'applies to all threads
  LOCAL x, Threads AS LONG, t AS MyType
  Threads = 5
  REDIM hThreads(1 TO Threads) AS LONG
  FOR x = 1 TO Threads
    t.sDatabase       = "sample.db3"
    t.sIpAddress      = "192.168.1.2" 'change this
    t.PortNumber      = 51234         'change this
    t.sql             = "select count(*) from parts"
    t.hEventReady     = CreateEvent (BYVAL 0, BYVAL %TRUE, BYVAL %FALSE, BYVAL 0)
    THREAD CREATE Test(VARPTR(t)) TO hThreads(x)
    WaitForSingleObject t.hEventReady,%INFINITE
    CloseHandle t.hEventReady
  NEXT
  waitformultipleobjects Threads, hThreads(1),%True,%INFINITE
  FOR x = 1 TO Threads 'close all thread handles
    THREAD CLOSE hThreads(x) TO hThreads(x)
  NEXT
  ? gsResult,%MB_SYSTEMMODAL,"Recordsets"
END FUNCTION

THREAD FUNCTION Test(BYVAL t  AS MyType PTR) AS LONG
  ThreadSafeHelper t
END FUNCTION

SUB ThreadSafeHelper(BYVAL t AS MyType PTR) THREADSAFE
  DIM s() AS STRING
  LOCAL sDatabase,sIpAddress, sql AS STRING, PortNumber AS LONG

  'Assign local variables to pointed to memory addresses
  sDatabase  = TRIM$(@t.sDatabase)
  sIpAddress = TRIM$(@t.sIpAddress)
  PortNumber = @t.PortNumber
  sql = @t.sql
  'Now allocated, let same memory address be reused
  SetEvent @t.hEventReady'thread allocate, release event

  slConnect sIpAddress,PortNumber
  IF slGetErrorNumber = 0 THEN
    slOpen sDatabase, "C"
    IF slGetErrorNumber= 0 THEN
      slSelAry sql,s(),"Q9c"
      gsResult+= JOIN$(s(),$CR) + $CR
    ELSE
      gsResult+= "Database open error" + $CR
    END IF
    slDisconnect
  ELSE
    gsResult+="Could not connect" + $CR
  END IF
END SUB