【问题标题】:Not able to force sequential execution of thread in C++? DeadLock?无法在 C++ 中强制顺序执行线程?僵局?
【发布时间】:2016-08-27 20:47:04
【问题描述】:

我正在尝试从字符串线程中读取单词。意思是一个线程读一个单词,当所有单词读完后,所有线程也应该和平退出。在此示例中,字符串中有 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


【解决方案1】:

您从未通知条件变量。它从未醒来。所有线程都在等待某事发生。在print 函数结束时通知:

void print(int k)
{
   unique_lock<mutex> lk(m);
   int z = k;
   cv.wait(lk,[&]{return check_func(i,z);});            // Line 33
   cout<<"Thread no. "<<this_thread::get_id()<<" parameter "<<k<<"\n";
   i++;
   cv.notify_all();  // Wake up all waiting threads - the correct one will continue.
}

您还需要将全局变量i 初始化为零,否则您将出现未定义的行为。

【讨论】:

  • 他不需要在 main 中也有初始通知吗?
  • 没有。根据cppreference.com,使用谓词调用wait 等价于while( !pred() ) wait( lock ); -- 首先测试谓词。因此,除了线程 0 将立即执行然后通知之外,所有线程都将等待该条件。
猜你喜欢
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-17
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
相关资源
最近更新 更多