【发布时间】:2016-05-04 08:34:00
【问题描述】:
我想通过使用 Multithreading 一次提取一个单词来阅读一个段落。每个线程应该读一个字,当段落结束时,他们应该和平退出。我知道不应该以这种方式使用线程,因为那样没有优势。但我想这样做,以便在需要时检查线程如何按顺序工作。我试过了,但看起来程序正在进入死锁状态并且根本没有给出任何输出。字符串中有 11 个单词,我正在使用 4 个线程。
#include <iostream>
#include <mutex>
#include <sstream>
#include <thread>
#include <chrono>
#include <condition_variable>
using namespace std;
stringstream s("Japan US Canada UK France Germany China Russia Korea India Nepal");
int count = 0;
string word;
condition_variable cv;
mutex m;
int i = 0;
bool check_func(int i,int k)
{
return i == k;
}
void print(int k)
{
while(count < 11) // As there are 11 words
{
unique_lock<mutex> lk(m);
int z = k;
cv.wait(lk,[&]{return check_func(i,z);}); // Line 33
s >> word;
cout<<word<<" ";
i++;
cv.notify_all();
count++;
}
return;
}
int main()
{
thread threads[4];
for(int i = 0; i < 4; i++)
threads[i] = thread(print,i);
for(auto &t : threads)
t.join();
return 0;
}
【问题讨论】:
标签: multithreading c++11 mutex deadlock