很高興c++11的標準庫可以#include <thread>了。boost早就提供了類似功能。這時候考慮下開發商、物業公司聯合阻礙成立業主委員會的藉口之一:
會妨礙事情的正常進展,推斷也許他們也是c++的長期使用者:)
1、pthread_xx的封裝
stl提供了(目前)五個頭文件以支持多線程:atomic(提供原子操作功能)、thread(線程模型封裝)、mutex(互斥量)、condition_variable(條件變量)、future
只使用win32的c++程序員可能對提供的線程庫感覺很陌生。事實上,它看起來的確是pthread_xx的c++封裝。如果對pthread不熟悉的話,可以參考https://computing.llnl.gov/tutorials/pthreads/
即便如此,在windows下創建一個默認參數的線程已經變得如此簡單了:
#include <iostream>
#include <thread>
using namespace std;
void thread_1()
{
cout << "hello from thread_1" << endl;
}
int main(int argc, char **argv)
{
thread t1(thread_1);
/**
join()相當於調用了兩個函數:WaitForSingleObject、CloseHandle,事實上,在vc12中也是這麼實現的
*/
t1.join();
return 0;
}
由於在thread的構造函數中調用了bind,線程函數的原型也簡單,不用嚴格寫成 void* (*FUN)(void*)的形式了。
甚至可以調用c++的成員函數:
#include <iostream>
#include <thread>
using namespace std;
class thread_c
{
public:
void thread_1()
{
cout << "hello from class member function" << endl;
}
};
int main(int argc, char **argv)
{
thread t1(&thread_c::thread_1, thread_c());
t1.join();
return 0;
}
沒錯,封裝後的thread class也丟失了一些系統級特性,比如,創建線城時你沒法設置參數,習慣使用CREATE_SUSPENDED 參數調用_beginthread的windows開發者可能會特別不習慣。要實現諸如等待的運行方式,mutex、condition_variable這兩個頭文件就能用上了:
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <condition_variable>
using namespace std;
condition_variable cv;
mutex mtx;
void thread_1()
{
unique_lock<mutex> ulock(mtx);
cv.wait(ulock);
cout << "hello from thread_1" << endl;
}
int main(int argc, char **argv)
{
thread t1(thread_1);
this_thread::sleep_for(chrono::seconds(1));
cv.notify_one();
t1.join();
return 0;
}
condition_variable頭文件對應了pthread_cond_xx一簇函數的功能實現。condition_variable::wait接受一個unique_lock<mutex>& 類型的參數。需要注意的是,所有的wait成員函數調用都必須使用同一個"mutex"對象來構造unique_lock(可以由std::unique_lock::mutex()函數返回)pthread_cond_wait的解釋要比stl的庫文檔上對wait函數的解釋清楚。mutex對象對條件對象進行保護,調用者要先鎖住互斥量傳遞給wait函數,wait函數把調用線程放到等待條件的線程列表上,然後對互斥量解鎖,這樣才能再次去鎖住mutex對象進行wait操作(試想如果沒有這個機制,多個線程同時對條件對象調用wait)。開始等待條件發生。當wait()函數返回的時候,互斥量又要被鎖住。
2、future
此頭文件實現了對指定數據提供者提供的數據進行異步訪問的機制。裏面包含的及個重點類:
future 能從作爲供給源的對象或者函數獲取值,如果是不同線程,則同步此操作
promise 保存能被future對象獲取的值
#include <iostream> // std::cout
#include <functional> // std::ref
#include <thread> // std::thread
#include <future> // std::promise, std::future
#include <string>
using std::string;
class thread_c
{
public:
void print_int(std::future<string>& fut) {
std::cout << "value: " << fut.get() << '\n';
}
};
int main()
{
std::promise<string> prom;
std::future<string> fut = prom.get_future();
thread_c thread_obj;
std::thread th1(&thread_c::print_int, thread_obj, std::ref(fut));
prom.set_value("hello future !");
th1.join();
return 0;
}
shared_future 接口與future類似(從名稱來看是一樣的),不同的是它可以拷貝,也可以多次取值。可以通過shared_future的構造函數隱式或者調用future::share
來顯式將一個future對象轉變成shared_future
#include <iostream> // std::cout
#include <functional> // std::ref
#include <thread> // std::thread
#include <future> // std::promise, std::future
#include <string>
using std::string;
class thread_c
{
public:
~thread_c()
{
std::cout << "thread_c object destructed." << std::endl;
}
public:
void print_int(std::shared_future<string>& fut) {
std::cout << "value: " << fut.get() << '\n';
}
};
int main()
{
std::promise<string> prom;
std::shared_future<string> fut = prom.get_future();
thread_c thread_obj;
const int thread_num = 10;
std::thread threads[thread_num];
for (int i = 0; i < thread_num; i++)
{
threads[i] = (std::thread(&thread_c::print_int, std::ref(thread_obj), std::ref(fut)) );
}
prom.set_value("hello future !");
// c++11支持的for語法
for (auto& th : threads) th.join();
return 0;
}
3、atomic 提供原子操作實現。裏面就兩個類aotmic、atomic_flag,好像沒啥好說的
4、幾個函數
std::call_once 包含在mutex中,看名字也知道,它能保證某個操作只進行一次
#include <iostream>
#include <functional>
#include <thread>
#include <future>
#include <string>
using std::string;
class thread_c
{
protected:
std::once_flag _once_flag;
public:
void thread_fun(int thread_no)
{
std::this_thread::sleep_for(std::chrono::microseconds(1000000));
std::call_once(_once_flag, std::bind(&thread_c::once_func, this, thread_no));
}
protected:
void once_func(int x)
{
std::cout << "called by thread " << x << std::endl;
}
};
int main()
{
thread_c thread_obj;
const int thread_num = 10;
std::thread threads[thread_num];
for (int i = 0; i < thread_num; i++)
{
threads[i] = std::thread(&thread_c::thread_fun, std::ref(thread_obj), i+1) ;
}
for (auto& th : threads) th.join();
return 0;
}
std::async 包含在future中。它能異步執行某個函數,將結果以future對象的形式返回
#include <iostream>
#include <functional>
#include <thread>
#include <future>
using std::cout;
using std::endl;
class thread_c
{
public:
int thread_fun(int num)
{
cout << "calculating....." << endl;
int count = num;
for (int i = 0; i < num; i++)
{
count++;
}
cout << "end calculate" << endl;
return count;
}
};
int main()
{
thread_c thread_obj;
std::future<int> ret = std::async(std::bind(&thread_c::thread_fun, &thread_obj, 10000));
cout << "async get value = " << ret.get() << endl;
return 0;
}
以上代碼在visual studio 2013編譯,gcc-4.9.2對c++11提供了完整的支持。如果兩個編譯都沒安裝,可以使用c++的在線編譯器