设为首页 加入收藏

TOP

c11的并发编程1
2012-11-01 09:13:23 来源: 作者: 【 】 浏览:362
Tags:c11 并发 编程
    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规范包括并发编程(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 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 <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;
   
    }
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇使用指针实现字符串的排序 下一篇c语言日期转化的问题

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: