是否可以在全球范围内声明一个提升线程

Is it possible to declare a boost thread globally?

本文关键字:一个 线程 声明 范围内 是否      更新时间:2023-10-16

您好,我想在全球范围内声明一个Boost线程并以后初始化。所以:

#include <iostream>
using namespace std;
boost::thread t;
void some_func()
{
    printf("hello worldn");
}
int main()
{
    t(some_func);
    return 0;
}

它正在返回有关初始化的错误。

error: no match for call to ‘(boost::thread) (void (&)())

那么我该如何初始化?

edit ::我想这样做的原因是因为我想根据条件产生线程。因此,在伪代码中:

    if (cond A satisfied)
        spawn thread_A
   if (cond B satisfied)
          spawn thread_B

         // Do some stuff
         if (cond B satisfied)
          thread_B.join()
     if (cond A satisfied)
           thread_A.join()

如果线程没有全局范围,那么我不能这样做

t的默认构造函数初始化对象没有活动线程。为了解决此问题,您必须执行互换。

boost::thread(&some_func).swap(t);

或rvalue的分配(在C 11中):

t = boost::thread(&some_func);
相关文章: