Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do semaphores prevent instruction reordering?

I was looking for an awaitable equivalent of lock statements in C#. Some people suggest using a binary SemaphoreSlim in the following way:

await semaphore.WaitAsync().ConfigureAwait(false);
try
{
    //inner instructions
}
finally
{
    semaphore.Release();
}

I know it has some issues (e.g. it's not reentrant), but my biggest concern is with the instruction reeordering.

In plain old lock statements we have a guarantee that no inner instruction from the lock will be moved outside (before or after) the lock statement. Does the same hold for this semaphore solution? As far as I can see, the documentation doesn't mention this problem.

like image 294
tearvisus Avatar asked Oct 29 '22 15:10

tearvisus


1 Answers

SemaphoreSlim, and pretty much all of the other synchronization constructs, are built using a Monitor (or other types that are built on top of a Monitor) internally, which is exactly how a lock is implemented, giving you the same guarantees.

like image 158
Servy Avatar answered Nov 15 '22 04:11

Servy