我使用std::thread
编写了一个多线程C++程序,如下所示:
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
const int threadNum = 4;
mutex mt[threadNum];
condition_variable cv[threadNum];
thread threadList[threadNum];
bool threadWork[threadNum];
void work(int id) {
while (true) {
unique_lock<mutex> lck(mt[id]);
cv[id].wait(lck, [&]() { return threadWork[id]; }); // wait for incoming tasks
// do something
threadWork[id] = false;
cv[id].notify_all();
}
}
int main() {
for (int i = 0; i < threadNum; i ++) {
threadWork[i] = false;
threadList[i] = thread(work, i);
}
while (true) {
for (int i = 0; i < threadNum; i ++) {
// allocate tasks for each threads
threadWork[i] = true;
cv[i].notify_all();
}
for (int i = 0; i < threadNum; i ++) {
// wait until all tasks finish
unique_lock<mutex> lck(mt[i]);
cv[i].wait(lck, [&]() { return !threadWork[i]; });
cout << "Finish thread " << i << endl;
}
// do something
}
for (int i = 0; i < threadNum; i ++)
threadList[i].join();
return 0;
}
字符串
在程序的迭代过程中,主线程和子线程交替执行,主线程首先为多个子线程分配任务,所有线程完成任务后,主线程将汇总信息并进行其他计算。
但是,在执行过程中,程序会随机地在几次迭代后崩溃或陷入死锁。我不知道为什么会发生这种情况。这是什么问题?
我的环境:ubuntu 22.04,g++ 11.4
1条答案
按热度按时间kyxcudwk1#
下面代码中的注解:
字符串
对于你的实验,你应该尝试一些更简单的方法,比如说,从一个受保护的数据块开始。下面是一个例子。
请注意,在下面的代码中,工作线程等待一个唯一的条件变量,告诉它们需要做一些事情。
我还添加了一个简单的机制,一旦工作完成,就可以优雅地从程序中退出。这和其他部分一样重要,注意原子<>的使用,它保证所有核心都会在值发生变化时看到。
型