Xin vui lòng, bất cứ ai có thể giải thích làm thế nào để sử dụng và tạo ra một unique_lock trong c + +? Nó nên được sử dụng cả hai để có được loại trừ lẫn nhau với bất kỳ thủ tục của màn hình và để có thể thực hiện wait() trên biến điều kiện ... Tôi không hiểu từ tài liệu hướng dẫn như thế nào tôi phải tạo ra nó. Là một mutex cần thiết? Đây là một pseudo-code:Làm thế nào để sử dụng/tạo unique_lock trong c + +?
/* 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();
}
-1 _not_ ngoại lệ an toàn. – ildjarn