![]() finally LeaveCriticalSection() end block to protect the lock release, and prevent any dead lock of your application.ĭelphi is perfectly thread-safe if you protect your shared data with a lock, i.e. Some wrongly designed multi-threaded applications can actually be slower than mono-threaded apps!Īnd do not forget that if your code inside the critical section may raise an exception, you should always write an explicit try. So the shorter the critical section is, the faster your application is. Between `EnterCriticalSection` and `LeaveCriticalSection`, only one thread will be running: other threads will wait in `EnterCriticalSection` call. Using a local variable makes the critical section shorter, therefore your application will better scale and make use of the full power of your CPU cores. InterlockedExchange / InterlockedIncrement functions are low-level asm opcodes with a LOCK prefix (or locked by design, like the XCHG EDX, opcode), which will indeed force the cache coherency for all CPU cores, and therefore make the asm opcode execution thread-safe.įor instance, here is how a string reference count is implemented when you assign a string value (see _LStrAsg in System.pas - this is from our optimized version of the RTL for Delphi 7/2002 - since Delphi original code is copyrighted): With multi-threading, you are not sure that the code you write, via individual instructions, is executed as expected, when it deals with shared variables. ![]() Since code expects the data to be coherent, some multi-thread programs may behave wrongly. ![]() ![]() ![]() Another issue which may lead into race condition is two threads writing to a resource at the same time: it's impossible to know which value will be stored afterward. The CPU per-core cache is just one of the possible issues, which will lead into reading wrong values. "protect your shared variables with locks (aka critical sections), because you are not sure that the data you read/write is the same for all threads". ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |