一般人很少使用ACE::Thread,因为ACE的代码过于笨重,intel的TBB由于license的问题,商业使用要收费的,而且微软的PPL和TBB 很相似,没有使用tbb的必要。
我考虑过把做过的一些concurrency和parallelism的c++库开源,但是涉及到和启明星辰说不清楚的版权和保密问题,最终一直搁浅。
c++11规范包括并发编程(www.cppentry.com),c++开始全速追赶java.
下面举个例子
每一个线程都有自己的id,windows 和linux 都是如此
#include <thread>
#include <iostream>
#include <vector>
void hello(){
std::cout 《 “Hello from thread ” 《 std::this_thread::get_id() 《 std::endl;
}
int main(){
std::vector<std::thread> threads;
for(int i = 0; i < 5; ++i){
threads.push_back(std::thread(hello));
}
for(auto& thread : threads){
thread.join();
}
return 0;
}
理论上应该打印出
Hello from thread 140276650997504
Hello from thread 140276667782912
Hello from thread 140276642604800
Hello from thread 140276676175616
实际是
Hello from thread Hello from thread Hello from thread Hello from thread 3078413168
Hello from thread 3067923312
3057433456
30364537443046943600
这是因为线程被抢占的,当打印出一部分的时候,输出流被抢占了
lambda是c++11的一个新特性,非常类似java的callable
#include <thread>
#include <iostream>
#include <vector>
int main(){
std::vector<std::thread> threads;
for(int i = 0; i < 5; ++i){
threads.push_back(std::thread([](){
std::cout 《 “Hello from thread ” 《 std::this_thread::get_id() 《 std::endl;
}));
}
for(auto& thread : threads){
thread.join();
}
return 0;
}