Are threads waiting on a lock FIFO?

后端 未结 5 1864
被撕碎了的回忆
被撕碎了的回忆 2021-01-05 03:13

Let\'s say I have the following code

static class ...
{
    static object myobj = new object();

    static void mymethod()
    {
        lock(myobj)
                


        
5条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 04:10

    It is not clear from your code how does myobj get to be visible inside mymethod. Looks like var myobj is a local stack variable at the declaration scope (since is var). In that case it may be that each thread will have a separate instance of it and the mymethod will not block.

    Update

    About the whole FIFO argument, some background info is necessary: the CLR does not provide syncronization. It is the CLR host that provides this as a service to the CLR runtime. The host implements IHostSyncManager and other interfaces and provides the various syncronisation primitives. This may seem irelevant as the most common host is the typical application host (ie. you compile into and exe) and this deffers all synchronization to the OS (your old Petzold book primitives in Win32 API). However there are at least two more major hosting evironments: the ASP.Net one (I'm not sure what this does) and SQL Server. What I can tell for sure is that SQL Server provides all primitives on toop of the SOS (which is basically an user more operating system), never touching the OS primitives, and the SOS primitives are unfair by design to avoid lock convoys (ie. guranteed no FIFO). As the link in the other response already pointed out, the OS primitives have started also to provide unfair behavior, for the same reason of avoiding lock convoys.

    For more information about lock convoys you should read the Rick Vicik articles at Designing Applications for High Performance:

    Lock Convoy

    FIFO locks guarantee fairness and forward progress at the expense of causing lock convoys. The term originally meant several threads executing the same part of the code as a group resulting in higher collisions than if they were randomly distributed throughout the code (much like automobiles being grouped into packets by traffic lights). The particular phenomenon I’m talking about is worse because once it forms the implicit handoff of lock ownership keeps the threads in lock-step.

    To illustrate, consider the example where a thread holds a lock and it gets preempted while holding the lock. The result is all the other threads will pile up on the wait list for that lock. When the preempted thread (lock owner at this time) gets to run again and releases the lock, it automatically hands ownership of the lock to the first thread on the wait list. That thread may not run for some time, but the “hold time” clock is ticking. The previous owner usually requests the lock again before the wait list is cleared out, perpetuating the convoy

提交回复
热议问题