你的职能
void add() {
this->x = x + 1;
thread t1(print, ref(mtx), ref(cv), x);
t1.join();
}
创建一个线程,然后等待(
join()
)直到线结束。因为你的线程函数
void print(mutex & mtx, condition_variable & convar, int x) {
if (x < 5){
unique_lock<mutex> lock(mtx);
convar.wait(lock); // waits if x < 5
}
// ...
和
x
可能是(您没有初始化它)<5您的死锁。
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <condition_variable>
using namespace std;
void print(mutex & mtx, condition_variable & convar, int x)
{
if (x < 5) {
unique_lock<mutex> lock{ mtx };
convar.wait(lock);
} else {
convar.notify_all();
cout << "asdasd\n";
}
}
class foo {
private:
mutex mtx;
condition_variable cv;
int x{ 0 };
std::vector<thread> threads;
public:
void add() {
++x;
threads.push_back(thread(print, ref(mtx), ref(cv), x));
}
~foo() {
for (auto &t : threads)
t.join();
}
};
int main() {
foo f;
f.add();
f.add();
f.add();
f.add();
f.add();
}