look you must understand atomic operation very well before you can use them ...
p.s interlockcompare exchange is pointless on local (stack) variables ... each thread has its own current com access var. use global.
try // avoid deadlocks while not icx ( threadusingcom, myId, 0)<>,0 do spinwait;send_very_quickly(somedata);finalyicx(thethreadusingcom,0,myId);
In my code CurrentComAccess is just the (temp) result of icx, not the shared variable. The shared variable (private ComAccess: Integer;) is defined as variable of the thread class, is this 'global' enough?
every thread instance will have it own variable
in my programm I use Synaser for serial communication and Synapse for UDP. For receiving, each port has its own thread polling BlockSerial.RecvByte (UDPBlockSocket.RecvPacket respectively). Sending is always done via main thread. In Synaser I experienced crashes, probably when the polling thread and the main thread access the BlockSerial simultaniously (but not to sure about that). Thus I added some blocking mechanism with boolean variables. I thought boolean variables are thread safe, but it seems that they are not suitable for interlocks. Using critical sections I'd like to avoid, as for each single poll the critical section has to be entered end left again (performance).
but found out the opposite the hard way:
It's very simple and robust. You only need follow some rules:
TCriticalSection is most simple way to implement thread-safe for shared objects.
Note, that TThreads is NOT shared objects!
But creating locking mechanisms inside TThread cause troubles.
I believe these rules make it work fine, but may be to limited in some szenarios.
Machine word based variables (Integer, Boolean, Pointer, etc) is thread-safe, but not atomic, and not applicable to shared lock implementation.