Please, can anybody explain how to use and create an unique_lock in c++?
It should be used both to get mutual exclusion to any procedure of the monitor and to be able to perform wait() on the condition variable…I’m not understanding from the documentation how I am supposed to create it. Is necessary a mutex? Here is a pseudo-code:
/* compile with g++, flags -std=c++0x -lpthread */
#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>
#include <string.h>
#include <unistd.h>
class monitorTh {
private:
std::mutex m;
std::condition_variable waitP;
std::condition_variable waitC;
char element[32];
std::unique_lock::unique_lock l;
public:
void produce(char* elemProd) {
l.lock();
if (/*already_present_element*/) {
waitP.wait(l);
}
else {/*produce element*/}
l.unlock();
}
void consume() {
/*something specular*/
}
};
int main(int argc, char* argv[]) {
monitorTh* monitor = new monitorTh();
char prodotto[32] = "oggetto";
std::thread producer([&]() {
monitor->produce(prodotto);
});
std::thread consumer([&]() {
monitor->consume();
});
producer.join();
consumer.join();
}
std::unique_lockuse the RAII pattern.When you want to lock a mutex, you create a local variable of type
std::unique_lockpassing the mutex as parameter. When the unique_lock is constructed it will lock the mutex, and it gets destructed it will unlock the mutex. More importantly: If a exceptions is thrown, thestd::unique_lockdestructer will be called and so the mutex will be unlocked.Example: