Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4134811
  • 博文数量: 447
  • 博客积分: 1241
  • 博客等级: 中尉
  • 技术积分: 5786
  • 用 户 组: 普通用户
  • 注册时间: 2011-01-27 06:48
个人简介

读好书,交益友

文章分类

全部博文(447)

文章存档

2023年(6)

2022年(29)

2021年(49)

2020年(16)

2019年(15)

2018年(23)

2017年(67)

2016年(42)

2015年(51)

2014年(57)

2013年(52)

2012年(35)

2011年(5)

分类: C/C++

2012-09-29 14:14:58

c11规范的出台,使c++开始追赶java,并超越c#。其实c++封装的Thread库非常多,开源的ACE::Thread,intel公司的TBB,微软vs2010自带Parallel Patterns Library,boost的Thread,收费的有justThread。
一般人很少使用ACE::Thread,因为ACE的代码过于笨重,intel的TBB由于license的问题,商业使用要收费的,而且微软的PPL和TBB 很相似,没有使用tbb的必要。
我考虑过把做过的一些concurrency和parallelism的c++库开源,但是涉及到和启明星辰说不清楚的版权和保密问题,最终一直搁浅。
c++11规范包括并发编程,c++开始全速追赶java。
下面举个例子
每一个线程都有自己的id,windows 和linux 都是如此
#include
#include
#include
void hello(){
    std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}
int main(){
    std::vector 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 140276659390208
 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
#include
#include
int main(){
    std::vector 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;
}
阅读(3830) | 评论(0) | 转发(0) |
0

上一篇:如何安装gcc 4.7

下一篇:软件架构和编码

给主人留下些什么吧!~~