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 = //动态分配
thread* t;
t = new thread[threadNum]; //结果
float *result = (float *)malloc(threadNum*sizeof(float)); for ( int i = ; i < threadNum; i++){
t[i] = thread(thread_func, i, i, &result[i]);
} for ( int i = ; 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指回自己。