Hmm... and what happens if a second thread enters the "if(aThreadEntered)" before the first one executed "aThreadEntered = true;" ? I don't think that you can implement synchronization without resorting to language locking primitives (probably if you use atomic variables, you can modify your example to make it work)
Originally posted by ankur rathi:
One way could be:
[ January 17, 2008: Message edited by: ankur rathi ]
1. Create a dummy file in the filesystem named "unlocked"
2. every running thread try to RENAME the file to "locked.pid". (pid a unique id identifying the thread)
e.g. by issuing os shell command: rename unlocked locked.pid
- this command is guaranteed to be atomic since a file cannot be of 2 names and once it is renamed another thread cannot rename it anymore since the 'unlocked' filename no longer exist and the 'rename' command simply fails
3. every thread check for the existence of a 'locked.pid' file where pid is its own unique id.
4. At the end, the thread having the 'lock' rename it back to 'unlocked'
5. Potential problem is if a thread exit without renaming the 'locked.pid' back to 'unlocked' all other threads cannot obtained the lock anymore.
This is the algorithm I designed (not tested) to achieve multi-tasking when I used a scripting language (Autoit3 - a window keystroke emulator) which doesn't have interprocess communication built-in.
posted 10 years ago
Another idea is to obtain some OS provided resource which cannot be shared by 2 threads e.g. open a socket for a common port, open a common file in random write mode (reading and append mode not work), etc. The OS guarantees only 1 thread can obtain the resource and each thread just check if the target resource has been obtained by it before executing the synchronized code