测试代码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
会发现报错
In file included from /usr/include/c++/5/thread:35:0,
from thread.cpp:1:
/usr/include/c++/5/bits/c++0x_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
#error This file requires compiler and library support \
解决方法是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加锁,更改一下代码
#include <thread>
#include <iostream>
#include <mutex>
using namespace std;
mutex mLock;
void run(int n){
for(int i = 0; i < 5; i++) {
mLock.lock();
cout << "thread" << n << endl;
mLock.unlock();
}
}
int main() {
cout << "hahahha" << endl;
thread t1(run, 1);
thread t2(run, 2);
t1.join();
t2.join();
return 0;
}
运行结果:
$ ./mythread
hahahha
thread1
thread1
thread1
thread1
thread1
thread2
thread2
thread2
thread2
thread2
因为在run函数中有可能会发现异常,导致unlock没有执行到,进程可能会挂死
解决办法是使用lock_guard,由lock_guard控制构造和析构流程,会自动unlock,运行结果是一样的。
void run(int n){
for(int i = 0; i < 5; i++) {
//mLock.lock();
lock_guard <mutex> guard(mLock);
cout << "thread" << n << endl;
//mLock.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 lock
cout << "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