
Correction 11/12/21 Added SLEEP after THREAD CREATE (required for thread allocation.)
SLEEP not needed if using WaitForMultipleObjects is used correctly (demonstrated using groups in below post #3.)
THREADCOUNT can return 0 or another incorrect value if a thread does not allocate using SLEEP.
The better solution is to use post #3 that uses WaitForSingleObjects.
Much easier than using pointers.
Global type array elements can be used and be thread safe
No need to use pointers, thread safe or critical section and no race conditions.
Return values from threads can use the thread number as an element of a global array and are also thread safe
If you don't want to use a TYPE a global array can be used and just pass the element number to process the data in the global(element) array.
Pass the thread number (1,2, ...) to the thread function and use it as a unique element to return values in a global array.
Code:
TYPE RecordType one AS STRING * 12 two AS LONG END TYPE GLOBAL gsRecord() AS RecordType 'global type array GLOBAL gsResult() AS STRING 'results from threads FUNCTION PBMAIN AS LONG 'program name many.bas 11/11/21 LOCAL x,maxthread AS LONG ' maxthread = 64 REDIM gsResult(1 TO maxthread) 'option array to receive data back REDIM gsRecord(1 TO maxthread) 'values to thread gsPass(threadnum).values REDIM hThread (1 TO maxthread) AS LONG 'thread handles FOR x = 1 TO maxthread 'for thread loop gsRecord(x).one = USING$("THREAD#",x) ' first value to thread gsRecord(x).two = x ' second value to thread THREAD CREATE Many(x) TO hThread(x) ' create thread SLEEP 1 'added this 11/12/21 to prevent thread from not allocating!! THREAD CLOSE hThread(x) TO hThread(x) ' close thread NEXT 'next DO:SLEEP 50:LOOP UNTIL THREADCOUNT = 1 'wait for threads to finish ? JOIN$(gsResult(),$TAB),,"Thread safe global type array" 'show values from threads END FUNCTION THREAD FUNCTION Many(BYVAL x AS LONG) AS LONG 'echo values back gsResult(x)=USING$("&_,#",TRIM$(gsRecord(x).one),gsRecord(x).two) END FUNCTION
Comment