Spinlock vs. Mutex

It’s very interesting to compare the active waiting of a spinlock with the passive waiting of a mutex. Let's continue our discussing from the previous lesson and make a comparison between these two.

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)?

Press + to interact
// 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 ...