When is pthread_spin_lock the right thing to use (over e.g. a pthread mutex)?

前端 未结 4 1756
小鲜肉
小鲜肉 2020-12-04 14:35

Given that pthread_spin_lock is available, when would I use it, and when should one not use them ?

i.e. how would I decide to protect some shared data structure with

4条回答
  •  醉话见心
    2020-12-04 15:09

    Spinlock has only interest in MP context. It is used to execute pseudo-atomical tasks. In monoprocessor system the principle is the following :

    1. Lock the scheduler (if the task deals with interrupts, lock interrupts instead)
    2. Do my atomic tack
    3. Unlock the scheduler

    But in MP systems we have no guaranties that an other core will not execute an other thread that could enter our code section. To prevent this the spin lock has been created, its purpose is to postpone the other cores execution preventing concurrency issue. The critical section becomes :

    1. Lock the scheduler
    2. SpinLock (prevent entering of other cores)
    3. My task
    4. SpinUnlock
    5. Task Unlock

    If the task lock is omitted, during a scheduling, an other thread could try to enter the section an will loop at 100% CPU waiting next scheduling. If this task is an high-priority one, it will produce a deadlock.

提交回复
热议问题