g++编译c++11 thread报错问题 及c++多线程操作
測(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
會(huì)發(fā)現(xiàn)報(bào)錯(cuò)
解決方法是g++參數(shù)添加“-std=c++11”,但接著編譯時(shí),又會(huì)報(bào)另一個(gè)問(wèn)題
$ 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解決辦法是編譯參數(shù)添加“-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因?yàn)閏out打印不是原子操作,會(huì)導(dǎo)致thread1和thread2混著打印
先試著使用mutex加鎖,更改一下代碼
運(yùn)行結(jié)果:
$ ./mythread
hahahha
thread1
thread1
thread1
thread1
thread1
thread2
thread2
thread2
thread2
thread2
因?yàn)樵趓un函數(shù)中有可能會(huì)發(fā)現(xiàn)異常,導(dǎo)致unlock沒(méi)有執(zhí)行到,進(jìn)程可能會(huì)掛死
解決辦法是使用lock_guard,由lock_guard控制構(gòu)造和析構(gòu)流程,會(huì)自動(dòng)unlock,運(yùn)行結(jié)果是一樣的。
也可以利用unique_lock,這個(gè)功能和lock_guard類(lèi)似,但提供的功能更多些,try_to_lock嘗試去lock,可通過(guò)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();} }運(yùn)行結(jié)果,偶爾能看到?jīng)]有持到鎖的情況。
$ ./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
總結(jié)
以上是生活随笔為你收集整理的g++编译c++11 thread报错问题 及c++多线程操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 模型描述的关系模式_你的项目该用哪种编程
- 下一篇: tomcat下list所有文件的目录