競爭條件
并發(fā)代碼中最常見的錯誤之一就是競爭條件(race condition)。而其中最常見的就是數(shù)據(jù)競爭(data race),從整體上來看,所有線程之間共享數(shù)據(jù)的問題,都是修改數(shù)據(jù)導致的,如果所有的共享數(shù)據(jù)都是只讀的,就不會發(fā)生問題。但是這是不可能的,大部分共享數(shù)據(jù)都是要被修改的。
而c++中常見的cout就是一個共享資源,如果在多個線程同時執(zhí)行cout,你會發(fā)發(fā)現(xiàn)很奇怪的問題:
#include <iostream>
#include <thread>
#include <string>
using namespace std;
// 普通函數(shù) 無參
void function_1() {
for(int i=0; i>-100; i--)
cout << "From t1: " << i << endl;
}
int main()
{
std::thread t1(function_1);
for(int i=0; i<100; i++)
cout << "From main: " << i << endl;
t1.join();
return 0;
}
你有很大的幾率發(fā)現(xiàn)打印會出現(xiàn)類似于From t1: From main: 64這樣奇怪的打印結果。cout是基于流的,會先將你要打印的內容放入緩沖區(qū),可能剛剛一個線程剛剛放入From t1:,另一個線程就執(zhí)行了,導致輸出變亂。而c語言中的printf不會發(fā)生這個問題。
使用互斥元保護共享數(shù)據(jù)
解決辦法就是要對cout這個共享資源進行保護。在c++中,可以使用互斥鎖std::mutex進行資源保護,頭文件是#include <mutex>,共有兩種操作:鎖定(lock)與解鎖(unlock)。將cout重新封裝成一個線程安全的函數(shù):
#include <iostream>
#include <thread>
#include <string>
#include <mutex>
using namespace std;
std::mutex mu;
// 使用鎖保護
void shared_print(string msg, int id) {
mu.lock(); // 上鎖
cout << msg << id << endl;
mu.unlock(); // 解鎖
}
void function_1() {
for(int i=0; i>-100; i--)
shared_print(string("From t1: "), i);
}
int main()
{
std::thread t1(function_1);
for(int i=0; i<100; i++)
shared_print(string("From main: "), i);
t1.join();
return 0;
}
修改完之后,運行可以發(fā)現(xiàn)打印沒有問題了。但是還有一個隱藏著的問題,如果mu.lock()和mu.unlock()之間的語句發(fā)生了異常,會發(fā)生什么?unlock()語句沒有機會執(zhí)行!導致導致mu一直處于鎖著的狀態(tài),其他使用shared_print()函數(shù)的線程就會阻塞。
解決這個問題也很簡單,使用c++中常見的RAII技術,即獲取資源即初始化(Resource Acquisition Is Initialization)技術,這是c++中管理資源的常用方式。簡單的說就是在類的構造函數(shù)中創(chuàng)建資源,在析構函數(shù)中釋放資源,因為就算發(fā)生了異常,c++也能保證類的析構函數(shù)能夠執(zhí)行。我們不需要自己寫個類包裝mutex,c++庫已經(jīng)提供了std::lock_guard類模板,使用方法如下:
void shared_print(string msg, int id) {
//構造的時候幫忙上鎖,析構的時候釋放鎖
std::lock_guard<std::mutex> guard(mu);
//mu.lock(); // 上鎖
cout << msg << id << endl;
//mu.unlock(); // 解鎖
}
可以實現(xiàn)自己的std::lock_guard,類似這樣:
class MutexLockGuard
{
public:
explicit MutexLockGuard(std::mutex& mutex)
: mutex_(mutex)
{
mutex_.lock();
}
~MutexLockGuard()
{
mutex_.unlock();
}
private:
std::mutex& mutex_;
};
為保護共享數(shù)據(jù)精心組織代碼
上面的std::mutex互斥元是個全局變量,他是為shared_print()準備的,這個時候,我們最好將他們綁定在一起,比如說,可以封裝成一個類。由于cout是個全局共享的變量,沒法完全封裝,就算你封裝了,外面還是能夠使用cout,并且不用通過鎖。下面使用文件流舉例:
#include <iostream>
#include <thread>
#include <string>
#include <mutex>
#include <fstream>
using namespace std;
std::mutex mu;
class LogFile {
std::mutex m_mutex;
ofstream f;
public:
LogFile() {
f.open("log.txt");
}
~LogFile() {
f.close();
}
void shared_print(string msg, int id) {
std::lock_guard<std::mutex> guard(mu);
f << msg << id << endl;
}
};
void function_1(LogFile& log) {
for(int i=0; i>-100; i--)
log.shared_print(string("From t1: "), i);
}
int main()
{
LogFile log;
std::thread t1(function_1, std::ref(log));
for(int i=0; i<100; i++)
log.shared_print(string("From main: "), i);
t1.join();
return 0;
}
上面的LogFile類封裝了一個mutex和一個ofstream對象,然后shared_print函數(shù)在mutex的保護下,是線程安全的。使用的時候,先定義一個LogFile的實例log,主線程中直接使用,子線程中通過引用傳遞過去(也可以使用單例來實現(xiàn)),這樣就能保證資源被互斥鎖保護著,外面沒辦法使用但是使用資源。
但是這個時候還是得小心了!用互斥元保護數(shù)據(jù)并不只是像上面那樣保護每個函數(shù),就能夠完全的保證線程安全,如果將資源的指針或者引用不小心傳遞出來了,所有的保護都白費了!要記住一下兩點:
-
不要提供函數(shù)讓用戶獲取資源。
std::mutex mu; class LogFile { std::mutex m_mutex; ofstream f; public: LogFile() { f.open("log.txt"); } ~LogFile() { f.close(); } void shared_print(string msg, int id) { std::lock_guard<std::mutex> guard(mu); f << msg << id << endl; } // Never return f to the outside world ofstream& getStream() { return f; //never do this !!! } }; -
不要資源傳遞給用戶的函數(shù)。
class LogFile { std::mutex m_mutex; ofstream f; public: LogFile() { f.open("log.txt"); } ~LogFile() { f.close(); } void shared_print(string msg, int id) { std::lock_guard<std::mutex> guard(mu); f << msg << id << endl; } // Never return f to the outside world ofstream& getStream() { return f; //never do this !!! } // Never pass f as an argument to user provided function void process(void fun(ostream&)) { fun(f); } };
以上兩種做法都會將資源暴露給用戶,造成不必要的安全隱患。
接口設計中也存在競爭條件
STL中的stack類是線程不安全的,于是你模仿著想寫一個屬于自己的線程安全的類Stack。于是,你在push和pop等操作得時候,加了互斥鎖保護數(shù)據(jù)。但是在多線程環(huán)境下使用使用你的Stack類的時候,卻仍然有可能是線程不安全的,why?
假設你的Stack類的接口如下:
class Stack
{
public:
Stack() {}
void pop(); //彈出棧頂元素
int& top(); //獲取棧頂元素
void push(int x);//將元素放入棧
private:
vector<int> data;
std::mutex _mu; //保護內部數(shù)據(jù)
};
類中的每一個函數(shù)都是線程安全的,但是組合起來卻不是。加入棧中有9,3,8,6共4個元素,你想使用兩個線程分別取出棧中的元素進行處理,如下所示:
Thread A Thread B
int v = st.top(); // 6
int v = st.top(); // 6
st.pop(); //彈出6
st.pop(); //彈出8
process(v);//處理6
process(v); //處理6
可以發(fā)現(xiàn)在這種執(zhí)行順序下, 棧頂元素被處理了兩遍,而且多彈出了一個元素8,導致`8沒有被處理!這就是由于接口設計不當引起的競爭。解決辦法就是將這兩個接口合并為一個接口!就可以得到線程安全的棧。
class Stack
{
public:
Stack() {}
int& pop(); //彈出棧頂元素并返回
void push(int x);//將元素放入棧
private:
vector<int> data;
std::mutex _mu; //保護內部數(shù)據(jù)
};
//下面這樣使用就不會發(fā)生問題
int v = st.pop(); // 6
process(v);
但是注意:這樣修改之后是線程安全的,但是并不是異常安全的,這也是為什么STL中棧的出棧操作分解成了兩個步驟的原因。(為什么不是異常安全的還沒想明白。。)
所以,為了保護共享數(shù)據(jù),還得好好設計接口才行。