我從https://en.cppreference.com/w/cpp/thread/condition_variable/wait讀到wait()“原子解鎖鎖”。我怎么看這個std::cout?我試圖更好地理解條件變數的實際作用。我在下面寫了一個嘗試。
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
condition_variable cv;
mutex m;
bool stopped = false;
void f1() {
unique_lock<mutex> ul{m};
cout << "f1: " << ul.owns_lock() << endl;
cv.wait(ul, [&]{
cout << "f1: " << ul.owns_lock() << endl;
return stopped;
});
cout << "f1 RUNNING\n";
cout << "f1: " << ul.owns_lock() << endl;
}
void f2() {
lock_guard<mutex> lg{m};
cout << "f2 RUNNING\n";
}
int main() {
unique_lock<mutex> ul{m};
thread t1(&f1);
thread t2(&f2);
cout << ul.owns_lock() << endl;
this_thread::sleep_for(chrono::seconds(1));
stopped = true;
cv.notify_one();
cout << ul.owns_lock() << endl;
ul.unlock();
cout << ul.owns_lock() << endl;
this_thread::sleep_for(chrono::seconds(1));
t1.join();
t2.join();
return 0;
}
uj5u.com熱心網友回復:
std::unique_lock并std::lock_guard使用滿足BasicLockable要求的任何型別別。因此,只需撰寫您自己的包含 a 的類std::mutex,然后您就可以添加您想要的任何日志記錄。
更新:但是,std:condition_variable僅適用于std::mutex特定的,因此如果您撰寫自己的互斥體包裝類,那么您將不得不使用std::condition_variable_any。
例如:
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
struct LoggingMutex
{
mutex m;
void lock() {
cout << "Locking" << endl;
m.lock();
cout << "Locked" << endl;
}
bool try_lock() {
cout << "Attempting to lock" << endl;
bool result = m.try_lock();
cout << (result ? "Locked" : "Not locked") << endl;
return result;
}
void unlock() {
cout << "Unlocking" << endl;
m.unlock()
cout << "Unlocked" << endl;
}
};
condition_variable_any cv;
LoggingMutex lm;
bool stopped = false;
void f1() {
unique_lock<LoggingMutex> ul{lm};
cout << "f1: " << ul.owns_lock() << endl;
cv.wait(ul, [&]{
cout << "f1: " << ul.owns_lock() << endl;
return stopped;
});
cout << "f1 RUNNING\n";
cout << "f1: " << ul.owns_lock() << endl;
}
void f2() {
lock_guard<LoggingMutex> lg{lm};
cout << "f2 RUNNING\n";
}
int main() {
unique_lock<LoggingMutex> ul{lm};
thread t1(&f1);
thread t2(&f2);
cout << ul.owns_lock() << endl;
this_thread::sleep_for(chrono::seconds(1));
stopped = true;
cv.notify_one();
cout << ul.owns_lock() << endl;
ul.unlock();
cout << ul.owns_lock() << endl;
this_thread::sleep_for(chrono::seconds(1));
t1.join();
t2.join();
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516299.html
標籤:C c 11性病条件变量
下一篇:復制變數、創建臨時變數和移動語意
