Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1125715
  • 博文数量: 177
  • 博客积分: 761
  • 博客等级: 上士
  • 技术积分: 1518
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-04 22:37
文章分类

全部博文(177)

文章存档

2017年(1)

2016年(3)

2015年(33)

2014年(48)

2013年(60)

2012年(32)

分类: C/C++

2012-10-23 16:30:27

     线程在进行多个任务同时运行的时候,其消耗是相当小的。因此在诸多的多任务应用用起到了很关键的作用,尤其是几十,上百任务时就会有所体现,单单一两个不足以体现线程使用的优势。因此在开发多任务程序时掌握多线程的设计也至关重要。今天小试了下boost库中的thread,使用上和C下的thread没多大差别,毕竟是应用而不是写库,拿来看到即可用上。

点击(此处)折叠或打开

  1. #include <iostream>
  2. #include <cassert>
  3. #include <string>
  4. #include <iomanip>
  5. #include <boost/thread/thread.hpp>
  6. #include "boost/regex.hpp"
  7. using namespace std;
  8. void print_hello(void){
  9.     while(1){
  10.         std::cout<<"hello\n"<<std::endl;
  11.         std::cout<<pthread_self()<<std::endl;
  12.         sleep(1);
  13.     }
  14. }

  15. void print_nice(void){
  16.     while(1){
  17.         std::cout<<"nice\n"<<std::endl;
  18.         std::cout<<pthread_self()<<std::endl;
  19.         usleep(500000);
  20.     }
  21. }

  22. int main(int argc,char *argv[]) {
  23.     int i;
  24.     i=10;
  25.     std::cout<<std::endl;
  26.     boost::thread thread1(&print_hello);
  27.     boost::thread thread2(&print_nice);
  28.     cout<<dec<<i<<" "<<hex<<i<<endl;
  29.     cout<<dec<<thread1.get_id()<<std::endl;
  30.     cout<<dec<<thread2.get_id()<<std::endl;
  31.     thread1.join();
  32.     thread2.join();

  33.     return true;
  34. }
阅读(1515) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~