Search⌘ K

Spinlock vs. Mutex

Explore the differences between spinlock and mutex synchronization methods in C++. Learn how spinlocks use busy waiting causing high CPU load, while mutexes minimize core utilization during thread locking. This lesson helps understand practical CPU behavior and thread management techniques in concurrent programming.

We'll cover the following...

What will happen to the CPU load if the function workOnResource locks the spinlock for 2 seconds (lines 24 - 26)?

C++
// spinLockSleep.cpp
#include <iostream>
#include <atomic>
#include <thread>
class Spinlock{
std::atomic_flag flag;
public:
Spinlock(): flag(ATOMIC_FLAG_INIT){}
void lock(){
while( flag.test_and_set() );
}
void unlock(){
flag.clear();
}
};
Spinlock spin;
void workOnResource(){
spin.lock();
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
spin.unlock();
std::cout << "Work done" << std::endl;
}
int main(){
std::thread t(workOnResource);
std::thread t2(workOnResource);
t.join();
t2.join();
}

According to the theory, one of the four cores of PC will be fully utilized, and ...