Search code examples
multithreadinglinux-kernelspinlock

spin lock acquiring in linux


I was just wondering, suppose PC is having multi cores. There are three threads running in three different cores. Thread(T1) has acquired spin lock(S) in core(C1) and acquired lock by T1, same time T2 and T3 threads running in core C2 and C3 try to acquire lock and waiting for release of lock. once T1 thread releases lock which thread will acquire lock either T2 or T3? I am considering same priority of T2 and T3,and also waiting in different cores same time.


Solution

  • The linux kernel uses MCS spin locks. The gist is that waiters end up adding themselves to a queue. However, if there are 2 threads doing this, there are no guarantees as to who is going to succeed first.

    Similarly for more simplistic spin locks where the code just tries to flip the "taken" bit, there are no guarantees whatsoever. However, certain hardware characteristics can make it so certain cores have an easier time than others (if they share the same socket).

    You want to read https://www.kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.html

    I repeat: if 2 different threads compete for a lock, there is no guaranteed order in which they will take it and looking for one is wrong in the first place.