[fpc-devel] WriteBarrier

Martin Frb lazarus at mfriebe.de
Mon Aug 24 20:15:45 CEST 2020


On 24/08/2020 19:22, Jonas Maebe via fpc-devel wrote:
> On 24/08/2020 19:20, Jonas Maebe via fpc-devel wrote:
>> It's not paranoid, it is the only correct way to write the code.
> * if you don't want to use regular synchronisation primitives, like
> mutexes/signals/events/...
>

I have events in some cases.

The scenario is the following.
I have workers (TMyWorkerObject) (in threads).
There may bea (maybe huge) number of work items (processed by a few 
threads).

It can not be predicted in which order the items are going to be 
collected by the main thread.
So if the work item would *always* have to set an event, each item would 
need its own event. But I do not want to create hundreds or more of 
Events (one for each work item)


When the workitem is finished, the main thread may be waiting or not.

- If the main thread is waiting, then it does so by RtlEventWaitFor (on 
one global event), and the worker will do RtlEventSet.

- The case differs if the main thread is not yet waiting (and also may 
never do so, if it no longer needs the result / user cancellation).
-- In that case the item sets its state to "done". And *before* that 
does a WriteBarrier.
-- So if the main thread sees that the state is set to done, it knows it 
does not need an event to wait for. (main thread then does a ReadBarrier)

(state is exchanged interlocked, and the main thread indicates, if it 
waits for the event. So there is no race condition in exchanging state.)

If the state is "done" there is no waiting (no Event needed), and the 
worker is no longer accessed in the worker thread (no mutex needed)
It seems to me, in this case the Barriers are the easiest way.




More information about the fpc-devel mailing list