将线程创建为类数据成员

时间:2016-07-26 03:36:11

标签: c++ multithreading class pthreads qt-creator

我正在尝试创建一个线程并保持对它的引用作为类的成员,并且该线程调用该类的方法。这是代码:

EventQueue::EventQueue() {

    this->dispatcherThread = std::thread(&EventQueue::dispatchEvent, std::ref(*this));
    this->dispatcherThread.join();

}

我正在使用QtCreator进行构建。并得到这个错误:

  

/home/eventqueue.o:-1:在函数std::thread::thread<void (EventQueue::*)(), std::reference_wrapper<EventQueue> >(void (EventQueue::*&&)(), std::reference_wrapper<EventQueue>&&)': /usr/include/c++/4.9/thread:136: error: undefined reference to pthread_create'中:-1:错误:collect2:错误:ld返回1退出   状态

有什么问题?

我参考了这篇文章: Storing an std::thread object as a class member

但是我总是得到上面描述的编译错误

1 个答案:

答案 0 :(得分:3)

您需要链接到pthread库。

使用GCC,我们使用-pthread选项执行此操作。

例如:g++ -pthread ...