Spinlock versus Semaphore

后端 未结 11 755
广开言路
广开言路 2020-11-28 17:19

What are the basic differences between a semaphore & spin-lock?

When would we use a semaphore over a spin-lock?

11条回答
  •  伪装坚强ぢ
    2020-11-28 17:50

    From what is the difference between spin locks and semaphores? by Maciej Piechotka:

    Both manage a limited resource. I'll first describe difference between binary semaphore (mutex) and spin lock.

    Spin locks perform a busy wait - i.e. it keeps running loop:

    while (try_acquire_resource ()); 
     ...  
    release();

    It performs very lightweight locking/unlocking but if the locking thread will be preempted by other which will try to access the same resouce the second one will simply try to acquitre resource untill it run out of it CPU quanta.
    On the other hand mutex behave more like:

    if (!try_lock()) {
        add_to_waiting_queue ();
        wait();
    }
    ...
    process *p = get_next_process_from_waiting_queue ();
    p->wakeUp ();
    

    Hence if the thread will try to acquire blocked resource it will be suspended till it will be avaible for it. Locking/unlocking is much more heavy but the waiting is 'free' and 'fair'.

    Semaphore is a lock that is allowed to be used multiple (known from initialization) number of times - for example 3 threads are allowed to simultainusly hold the resource but no more. It is used for example in producer/consumer problem or in general in queues:

    P(resources_sem)
    resource = resources.pop()
    ...
    resources.push(resources)
    V(resources_sem)
    

    Difference between semaphore, mutex & spinlock?

    Locking in Linux

提交回复
热议问题