为了更好地理解C ++ 11中condition_variable的内部行为,我尝试编写自己的(简单/原始)条件变量类。它看起来像这样:
#include <iostream>
#include <thread>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <vector>
#include <memory>
using namespace std;
class condVar {
public:
void wait(unique_lock<mutex> & ul) {
stop_list_mutex.lock(); // synchronize with other wait/noify calls
ul.unlock();
// store mutex so we can unlock it afterwards
shared_ptr<mutex> stopm(new mutex());
stop_list.push_back(stopm);
stopm->lock();
stop_list_mutex.unlock();
// Stop now ...
stopm->lock();
ul.lock();
}
template<typename Predicate>
void wait(unique_lock<mutex> & ul, Predicate p) {
while (!p()) wait(ul);
}
void notify_one() {
lock_guard<mutex> lg(stop_list_mutex);
if (stop_list.size() > 0) {
stop_list.front()->unlock();
stop_list.erase(stop_list.begin());
}
}
void notify_all() {
lock_guard<mutex> lg(stop_list_mutex);
while (stop_list.size() > 0) {
stop_list.front()->unlock();
stop_list.erase(stop_list.begin());
}
}
private:
mutex stop_list_mutex;
vector<shared_ptr<mutex>> stop_list;
};
与“真正的”C ++ 11 condition_variable相比,一些简单的测试显示行为没有差异。上面的实现是否会在理论上起作用(除了我遗漏了大量的错误检查代码,如前后条件)?