linux-kerneloperating-systemmutexsemaphorethread-synchronization

Does mutex and semaphores "Busy wait" in a LINUX systems?


Recently I came to know that Sleep system call in a linux kernel will suspend the current calling thread to a suspended/blocked state, meaning they wont utilise the CPU until the mentioned time elapse. - perfectly understood.

Now coming to mutex and semaphores,

Mutex Locks:

acquire() {
while (!available)
; // busy wait    --> my doubt
available = false;;
}

release() {
available = true;
}

Semaphore locks:

wait(S) {
while (S <= 0)
; // busy wait --> my doubt
S--;
}
signal(S) {
S++;
}

P.S: these code snippets are taken from "operating systems concepts -9th edition" by ABRAHAM SILBERSCHATZ

My question:

I know that busy wait is not an efficient way to approach synchronisation problems, but from the code snippets mentioned above i got a doubt that using mutex and semaphores will end up in a busy wait ?? (though mutexes and semaphores being widely used to solve most sysnc problems).

Which inturn make me feel that using mutex & semaphores is not an efficient way to solve sync problems as it is going to consume CPU cycles (because it will not lead to suspended state rather spinning in a while loop ).

To be short : Does mutexes and semaphores busy waits rather putting the waiting thread thread to a suspended state ??

Thanks in advance !!. Kindly correct me if am wrong in my understanding !!


Solution

  • Does mutexes and semaphores busy waits

    No, internally those functions (e.g. Pthread mutexes functions like pthread_mutex_lock) use atomic machine instructions (coded in assembler) coupled with futex(7).

    For POSIX semaphores (see sem_overview(7)) the kernel scheduler would schedule other tasks. So it is not busy waiting.

    If no task is runnable, the kernel would sit in its idle loop waiting (without burning CPU cycles) for something (like an interrupt). So your laptop won't overheat and use too much battery in such case!

    Read also Operating Systems: Three Easy Pieces (freely downloadable). Look also on OSDEV if you want to develop some toy kernel. You could also study the source code of the Linux kernel since it is free software then ask on kernelnewbies. The standard C library and its pthread layer is also free software (so study GNU glibc or musl-libc source code).