在多个线程中使用cout可能会导致交错输出.
所以我试图用互斥锁来保护cout.
以下代码使用std :: async启动10个后台线程.线程启动时,会打印"Started thread ...".主线程按照创建顺序迭代后台线程的未来,并在相应的线程完成时打印出"Done thread ...".
输出正确同步,但在某些线程启动后有些线程已经完成(参见下面的输出),就会出现死锁.剩下所有后台线程,主线程正在等待互斥锁.
僵局的原因是什么?
当保留打印功能或for循环的一次迭代结束时,lock_guard应解锁互斥锁,以便其中一个等待线程能够继续.
为什么所有线程都挨饿?
码
#include <future>
#include <iostream>
#include <vector>
using namespace std;
std::mutex mtx; // mutex for critical section
int print_start(int i) {
lock_guard<mutex> g(mtx);
cout << "Started thread" << i << "(" << this_thread::get_id() << ") " << endl;
return i;
}
int main() {
vector<future<int>> futures;
for (int i = 0; i < 10; ++i) {
futures.push_back(async(print_start, i));
}
//retrieve and print the value stored in the …Run Code Online (Sandbox Code Playgroud)