今天想回顾下C++的线程功能,使用QT编译以下代码,没有问题。
#include <iostream> #include <thread> using namespace std; void work() { cout<<"pid="<<this_thread::get_id()<<endl; } int main(int argc, char *argv[]) { thread t1(work); // t1.join(); return 0; }
运行时竟然出错了
terminate called after throwing an instance of 'std::system_error' what(): Enable multithreading to use std::thread: Operation not permitted
原来是与pthread库有关系,解决方法,在.pro一程配置文件中加入以下内容
# 一般加上pthread就可以 LIBS += -pthread # 如果你的QT工程CONFIG中没有配置c++11,最好把下面两行也一并加上吧 QMAKE_CXXFLAGS += -pthread QMAKE_CXXFLAGS += -std=c++11
然后运行就正常了。