简体   繁体   English

创建一个线程作为类数据成员

[英]Creating a thread as a class data member

I am trying to create a thread and keep the reference to it as a memeber of the class, and the thread calls a method of the class. 我试图创建一个线程,并将对该线程的引用作为该类的成员,并且该线程调用该类的方法。 Here is the code: 这是代码:

EventQueue::EventQueue() {

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

}

I am using QtCreator to do the build. 我正在使用QtCreator进行构建。 And gets this error: 并得到此错误:

/home/eventqueue.o:-1: In function 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: error: collect2: error: ld returned 1 exit status /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 /usr/include/c++/4.9/thread:136:错误: 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的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 ':-1:错误:collect2:错误:ld返回1退出状态

What is the problem? 问题是什么?

I was referencing to this post: Storing an std::thread object as a class member 我指的是这篇文章: 将std :: thread对象存储为类成员

However I always get the compilation error described above 但是我总是会遇到上述编译错误

You need to link against the pthread library. 您需要链接到pthread库。

With GCC, we do this with the -pthread option. 对于GCC,我们使用-pthread选项来实现。

For example: g++ -pthread ... 例如: g++ -pthread ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM