在c++中执行特定操作后从派生线程返回

returning from spawned thread after a particular action in c++

本文关键字:派生 线程 返回 操作 c++ 执行      更新时间:2023-10-16

我是新的线程相关的概念。我有主函数的程序,在那里我调用函数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:设置条件后需要加入线程。这将阻塞主线程,直到另一个线程返回。