I found some code online that defines a semaphore class for C++:
#include <mutex>
#include <condition_variable>
#include <atomic>
using namespace std;
class Semaphore {
public:
Semaphore(int count_ = 0) : count(count_) {}
inline void notify()
{
unique_lock<mutex> lock(mtx);
count++;
cv.notify_one();
}
inline void wait()
{
unique_lock<mutex> lock(mtx);
while (count == 0) {
cv.wait(lock);
}
count--;
}
private:
mutex mtx;
condition_variable cv;
atomic<int> count;
};
Imagine I have 10 threads and 2 of them can "work" simultaneously. How would I write this in my main, making use of the above defined class? I would like some short illustrative example. I'm aware, that this definition is a weak semaphore, since some of the threads will starve others.
Aucun commentaire:
Enregistrer un commentaire