在c++中执行特定操作后从派生线程返回
returning from spawned thread after a particular action in c++
我是新的线程相关的概念。我有主函数的程序,在那里我调用函数a(),它使用boost生成一个线程(NewThread)。现在,作为线程的一部分,我对一些变量进行了一些初始化,然后启动了一个while(1)循环。
我想给函数b()当控制到达内部while(1),
当前正在到达b()而没有启动while循环。
请指引我。
void NewThread()
{
//initialization of some modules
//infinite while loop
while(1)
{
}
}
void a()
{
this->libThread = new boost::thread(boost::bind(&NewThread));
}
void b()
{
cout<<"function b";
}
int main()
{
a();
b();
}
您可以在c++11中使用类似的方法。注意,您需要为条件使用原子变量,而不能只使用布尔变量。您也可以使用条件变量。
#include <thread>
#include <atomic>
#include <memory>
std::unique_ptr<std::thread> t;
std::atomic<bool> condition(false);
void f() {
while(true) {
if(condition) {
return;
}
}
}
void a () {
t.reset(new std::thread(&f));
}
void b() {
condition = true;
t->join();
}
int main() {
a();
b();
}
update:设置条件后需要加入线程。这将阻塞主线程,直到另一个线程返回。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 使用基类中的派生方法运行线程,而无需使用模板
- 在派生自线程类的构造函数中传递字符串
- c++ 在派生函数中启动 OMP 线程
- 线程中的虚拟呼叫忽略派生类
- 将派生类指针的向量传递给线程
- 如何使派生类函数作为线程的启动例程?
- 在c++中执行特定操作后从派生线程返回
- Std::thread在对象中派生的线程,它何时终止?
- 构造执行派生类成员函数的线程
- 退出的Qt应用程序不会杀死派生的线程
- 在派生的线程中启动进程
- setrlimit()不影响派生的std::线程
- 如何验证运行时失败是否是由于派生了太多线程造成的
- 管理派生类中的线程生命周期