g++编译c++11 thread报错问题 及c++多线程操作
测试代码thread.cpp
#include <thread> #include <iostream> using namespace std;void run(int n){for(int i = 0; i < 5; i++) {cout << "thread " << n << endl;} } int main() {cout << "hahahha" << endl;thread t1(run, 1);thread t2(run, 2);t1.join();t2.join();return 0; }直接g++编译一下
g++ thread.cpp -o mythread
会发现报错
解决方法是g++参数添加“-std=c++11”,但接着编译时,又会报另一个问题
$ g++ thread.cpp -std=c++11 -o mythread /tmp/ccbLvKA8.o: In function `std::thread::thread<void (&)(int), int>(void (&)(int), int&&)': thread.cpp:(.text._ZNSt6threadC2IRFviEJiEEEOT_DpOT0_[_ZNSt6threadC5IRFviEJiEEEOT_DpOT0_]+0x93): undefined reference to `pthread_create' collect2: error: ld returned 1 exit status解决办法是编译参数添加“-lpthread”
$ g++ thread.cpp -std=c++11 -o mythread -lpthead /usr/bin/ld: cannot find -lpthead collect2: error: ld returned 1 exit status $ g++ thread.cpp -std=c++11 -o mythread -lpthread $ ./mythread hahahha thread1 thread1 threadthread2 thread2 thread2 thread2 thread2 1 thread1 thread1因为cout打印不是原子操作,会导致thread1和thread2混着打印
先试着使用mutex加锁,更改一下代码
运行结果:
$ ./mythread
hahahha
thread1
thread1
thread1
thread1
thread1
thread2
thread2
thread2
thread2
thread2
因为在run函数中有可能会发现异常,导致unlock没有执行到,进程可能会挂死
解决办法是使用lock_guard,由lock_guard控制构造和析构流程,会自动unlock,运行结果是一样的。
也可以利用unique_lock,这个功能和lock_guard类似,但提供的功能更多些,try_to_lock尝试去lock,可通过owns_lock判断是否持锁成功
void run(int n){for(int i = 0; i < 5; i++) {//mLock.lock();//lock_guard <mutex> guard(mLock);unique_lock <mutex> lock(mLock, try_to_lock);//try to lockcout << "thread" << n << ", lock result:" << lock.owns_lock() << endl;//mLock.unlock();} }运行结果,偶尔能看到没有持到锁的情况。
$ ./mythread
hahahha
thread1, lock result:1
thread1, lock result:1
thread1, lock result:1
thread1, lock result:1
thread1, lock result:1
thread2, lock result:0
thread2, lock result:1
thread2, lock result:1
thread2, lock result:1
thread2, lock result:1
总结
以上是生活随笔为你收集整理的g++编译c++11 thread报错问题 及c++多线程操作的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 模型描述的关系模式_你的项目该用哪种编程
- 下一篇: c++中的explicit关键字