System.SyncObjs.TLightweightSemaphore.Create: the AInitialCount parameter
Posted by jpluimers on 2020/12/16
Multi-threading is hard, knowing your primitives is important, but Embarcadero documentation is always far from complete, leading to [WayBack] System.SyncObjs.TLightweightSemaphore.Create: Please simply explain to me the parameters of this constructor, especially first, AInitialCount… – Jacek Laskowski – Google+
The concept of semaphores is universal (the free book [WayBack] The Little Book of Semaphores – Green Tea Press is great), but the implementation/wrapping can slightly differ, so on the [Archive.is] XE introduced TLightweightSemaphore.Create parameters:
Semaphore is used to allow ‘counted’ access. It allows access to as much owners as it has maximum count. If you wait on a semaphore (
WaitFor
) and wait succeeds, the semaphore’s count is decremented. When it drops to 0, no newWait
will succeed.When you call
Release
, the semaphore’s count is incremented which allows somebody else to own the semaphore.Parameters simply set the initial state for this count and maximum value of the counter. Usually you’ll both set to the same value.
If you intend to use semaphores, read this. Great book.
The Little Book of Semaphores – Green Tea Pressgreenteapress.com I know (theoretically) how a semaphore works. I even used this semaphore class in production code.
I want to create as many threads as there are cores in the processor (+ 1 additional, little loaded).fCoreController := TLightweightSemaphore.Create(TThread.ProcessorCount, TThread.ProcessorCount + 1);
But now it turned out that customers who have CPUs with one core (yes, there are those), this code blocks the remaining threads. And I am looking for a reason, maybe I misunderstand this semaphore. What doesAInitialCount
mean?ps. Delphi Seattle
AInitialCount is the number of entires a semaphore has left when created. If that is one less thanAMaxCount
that means you already gave one entry away. I just do a wild guess and say that you might do a Wait on the created semaphore shortly after creating it and in some other thread as well but since for one CPU yourAInitialCount
is only 1, one of them will block – possibly you created a deadlock situation here. +Stefan Glienke Ok, if I want threads to be given a semaphore so that they work when it’s open (thread execute ->Semaphor.WaitFor
) and I want to have as many threads as there are cores (+1 additional) then how should I createTLightweightSemaphore
object? What Primoz said at the end of the very first comment – put same value for both:TThread.ProcessorCount + 1
–jeroen
Leave a comment