Essentially, a critical section or some other form of synchronization (mutex, semaphore, etc) is required when a thread accesses memory that can be altered by another thread at the same moment. This covers GLOBAL and STATIC variables or any other block of memory. Local variables are automatically thread-safe as they are (generally speaking) stored on the stack allocated to each thread.
For example, the following simple thread function is NOT thread-safe, since more than once thread can read and update the variable at any moment and corrupt the value in the variable if a context-switch (thread switch) occurs before all bytes of the target variable are successfully written by a given thread. Image that the thread that is writing a new valu to th variable is switched aftr only 2 bytes of the variable have has their new values written to memory. If another thread tries to read the value during the switch, it will read part of the new value and part of the old value!
Code:
FUNCTION WorkerThread(BYVAL x AS LONG) AS LONG DIM Total AS GLOBAL CUX ' global variable! TOTAL = TOTAL * x / 100@@ END FUNCTION
BTW, you'll note that a thread function MUST receive a 32-bit LONG or DWORD and it must be BYVAL... your code omits this parameter.
Also, it looks like the functions your thread calls are using some form of GLOBAL variable storage (since you are not passing any parameters), so I would hazard a guess to say your code is far from thread-safe as it stands.

In summary - get a copy of Rector/Newcomer - consider it an investment in yourself!

------------------
Lance
PowerBASIC Support
mailto:[email protected][email protected]</A>
Leave a comment: