我有一个做一些多线程的C ++类。考虑下面的伪代码:
void MyClass::Open() {
loop_flag = true;
// create consumer_thread (infinite loop)
// create producer_thread (infinite loop)
}
void MyClass::Close() {
loop_flag = false;
// join producer_thread
// join consumer_thread
}
MyClass::~MyClass() {
Close();
// do other stuff here
}
请注意,consumer_thread,producer_thread及其相关函数都封装在MyClass中。调用者不知道他们的调用是多线程的,并且后台发生了什么。
现在,该类是更大程序的一部分。该程序具有一些初始的多线程来处理系统的配置,因为一次发生了很多事情。
像这样(伪代码):
int main() {
// create config_thread1 (unrelated to MyClass)
// create thread for MyClass::Open()
// ...
// join all spawned configuration threads
}
所以我的问题是,当我为链接到MyClass :: Open()的线程调用join()时(即,在main()中生成的配置线程),会发生什么?它是立即join()(因为MyClass :: Open()函数在创建producer_thread和consumer_thread之后才返回),还是等待producer_thread和consumer_thread完成(因此挂起了我的程序)。
在此先感谢您的帮助。在实现细节方面,我在Linux机器上使用Boost线程。
编辑添加此图:
main()
|
|
|
|--->configuration_thread (that runs MyClass::Open())
|
|
|----> producer_thread
|----> consumer_thread
如果我在configuration_thread()上调用join(),它会等到producer_thread()和Consumer_thread()完成还是立即返回(并且producer_thread()和Consumer_thread()继续运行)?
一个(非分离的)线程将是可操纵的,即使从该函数返回设置为运行的线程之后,直到它被加入为止。例子:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
void foo(){
std::cout << "helper: I'm done\n";
}
int main(){
cout << "starting helper...\n";
thread helper(foo);
this::thread::sleep_for(std::chrono::seconds(5));
cout << "helper still joignable?..." << (helper.joignable()?"yes!":"no...:(") << "\n";
helper.join();
cout << "helper joined!";
cout << "helper still joignable?..." << (helper.joignable()?"really?":"not anymore!") << "\n";
cout << "done!\n";
}
输出:
starting helper...
helper: I'm done
still joinable?...yes!
helper joined!
still joinable?...not anymore!
done!
至于该join
方法需要花费多少时间,我认为这没有指定,但是可以肯定它不必等待所有其他线程完成,否则就意味着只有一个线程可以加入所有其他。
从§30.3.5开始:
void Join();
要求:
joinable()
是true
效果:阻塞直到由代表的线程
*this
完成。同步:所代表的线程的完成
*this
与相应的成功join()
返回同步。[注意:操作*this
不同步。*-尾注*][...]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句