2014年01月19日 星期日 18:25
C++11标准引入了与并行计算相关的多个模块,包括thread、mutex、future、atomic等,理念非常先进,API非常容易使用。thread模块的示例代码如下:
#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
using namespace std;
using namespace std::this_thread;
void func1(int start) {
for(int i=start;i<start+5;i++) {
cout << get_id() << ":" << i << endl;
sleep_for(chrono::seconds(1));
}
}
int main(int argc,char **argv) {
auto n=thread::hardware_concurrency();
cout << "hardware concurrency: " << n << endl;
cout << "main thread id: " << get_id() << endl;
thread d(func1,1000);
d.detach();
vector<thread*> threads;
for(unsigned int i=0;i<2*n;i++) {
threads.push_back(new thread(func1,i*10));
}
for(auto x : threads) {
x->join();
}
sleep_for(chrono::seconds(1));
return 0;
}
需要注意两点:
1,thread对象本身不可拷贝(copy)。
2,示例代码需要使用g++ 4.8以上版本才可正常编译运行。参考编译指令:
g++ -o threads threads.cpp -lpthread -std=c++11
参考资料:
Zeuux © 2025
京ICP备05028076号