【问题标题】:How to thread a chain of while(true) inside classes to join without getting stuck? C++如何在不卡住的情况下在类中插入一系列 while(true) 以加入? C++
【发布时间】:2018-02-18 01:01:30
【问题描述】:

Chain1、Chain2、Chain3,所有的类结构都是一样的,只是真正的区别在于里面的线程Dofunction,所以除了那个DoFunction之外,它们本质上是同一个类。这不是在做类似于How do I use while true in threads? 的解决方案吗? 以下是我要完成的工作的总体思路。当我尝试加入时,第二个线程挂断了。

main()
{
   Chain1 generator;
   Chain2 preprocessor;
   Chain3 processor;

   // to communicate to the parent for data transfer
   processsor.makeChild(&generator);
   processor.makeChild(&preprocessor);

   // initialize the threads
   generator.init();
   preprocessor.init();
   processor.init();

   // join the threads
   generator.start();
   preprocessor.start(); // issue here hangs up here trying to join
   processor.start();
}

class Chain1 //or Chain2 or Chain3...
{
     init()
     {
         // stored as a class member
         chain_thread = std::thread(&Chain1::Dofunction, this); // or std::thread(&Chain::Chain2::Dofunction, this); // or std::thread(&Chain::Chain3::Dofunction, this);
     }
     start()
     {
        chain_thread.join();   
     }
     Dofunction()
     {
         while(true)
         {
             //...  different for each Chain1, Chain2, Chain3
         }
     }
}

【问题讨论】:

  • “不同”如何?我真的不明白这个问题。只需编写代码 - 有什么问题?
  • 我不确定我是否理解这个问题。根据所涉及变量的名称,我猜您尝试创建一个包含三个步骤的管道 - 生成、预处理和处理 - 其中生成器不断创建应该通过管道传递的新值,对吗?
  • 问题是什么?问题是什么?这些线程是否以某种方式进行通信?
  • // 加入线程 generator.start();预处理器.start(); // 这里的问题在这里挂断,试图加入 processor.start();
  • 我尝试加入的第二个线程挂断了。我不是在做与链接中的解决方案类似的事情吗?

标签: c++ multithreading join


【解决方案1】:

您似乎误解了std::thread::join 的目的。该功能不适用于启动线程。该函数阻塞调用者(基本上是你的主线程),直到线程(链线程)完成执行。

所以,基本上发生的事情是: 1. 在chainX::init() 函数中创建线程。线程从该点开始运行无限循环。 2.你join你的主函数中的线程,这基本上意味着你正在等待线程完成它们的执行(它们不是因为它们处于无限循环中?你没有显示里面发生了什么Dofunction)

您需要在 while 循环中设置中断条件。由于我不知道应该停止你的线程,以下只是伪代码:

Dofunction()
     {
         while(true)
         {
             //...  different for each Chain1, Chain2, Chain3
             if(work_done == true) break;
         }
     }

work_done 可以是检查工作队列是否为空或来自主线程的信号表明工作应该停止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2013-11-18
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多