If you use multi-threads to do something at the same time, that is a Synchronization.
You need to control threads to avoid Race Condition and Critical Section.
mutex and semaphore can solve the critical section.
But what’s different?
Mutex is an object and binary semaphore .
A semaphore is a signal, and a thread that is waiting on a semaphore can be signaled by another thread (more then 2 threads).
But you should notice that the wait and signal operations require to be executed in the correct order. Nevertheless, deadlocks will occur in semaphore.
Roughly, a mutex would be referred to as binary semaphore.
There are many dufferences, you may refer to this website.
https://www.guru99.com/mutex-vs-semaphore.html
How can we use semaphore?
// header
#include <semaphore.h>
class Foo {
private:
//declaration
sem_t firstDone;
sem_t secondDone;
public:
Foo() {
// initialize
sem_init(&firstDone, 0, 0);
sem_init(&secondDone, 0, 0);
}
void first(function<void()> printFirst) {
printFirst();
//broadcast signl: first has done
sem_post(&firstDone);
}
void second(function<void()> printSecond) {
// waiting the signal from firstDone
sem_wait(&firstDone);
printSecond();
//broadcast signl: second has done
sem_post(&secondDone);
}
void third(function<void()> printThird) {
// waiting the signal from secondDone
sem_wait(&secondDone);
printThird();
}
};
Ref.
https://www.guru99.com/mutex-vs-semaphore.html
https://sls.weco.net/node/21326
https://jasonblog.github.io/note/linux_system/mutex_yu_semaphore_zui_da_de_cha_yi_shi.html