c++11是VS2012後支持的新標准,為並發編程提供了方便的std::thread。
使用示例:
#include <thread>
void thread_func(int arg1, int arg2, float* arg3){
arg3 = (arg1*1.0)/(arg1 + arg2);
cout << "arg1 / (arg1 + arg2) = " << arg3 << endl;
return;
}
void main(){
//線程數
int threadNum = 3
//動態分配
thread* t;
t = new thread[threadNum];
//結果
float *result = (float *)malloc(threadNum*sizeof(float));
for ( int i = 0; i < threadNum; i++){
t[i] = thread(thread_func, i, i, &result[i]);
}
for ( int i = 0; i < threadNum; i++){
//t[i].detach(); //主進程不等子進程運行完
t[i].join(); //主進程等
}
//post-processing towards result...
}
當需要利用類成員函數( MyClass::thread_func )來創建子線程時,需如下碼碼:
t[i] = thread(std::mem_fn(&MyClass::thread_func), Object, args..);
如果thread_func為static,則不用寫object。否則需要,如主進程所調函數也為該類成員,則傳入this指回自己。