boost线程

来源:互联网 发布:同花顺l2数据 编辑:程序博客网 时间:2024/06/05 03:52
1包含thread头文件及使用boost命名空间#include<boost/thread.hpp>
2.使用等待当前线程的成员函数join()一直阻塞等待,直到当前线程结束。time_join()等待当前线程结束或者最多等待多少时间后返回[当当前线程已经结束但等待时间还未到时也返回]
3.几种使用方法第一种方式:最简单方法
  1. void print_string( const string &str );  
  1.  
  1. int _tmain(int argc, _TCHAR* argv[])  
  1. {        
  1.     boost::thread test1( print_string, "hello" );  
  1.    test1.join();  
  1.    return 0;
第二种方式:在类内部创建线程1)类内部静态方法启动线程class HelloWorld{public:static void hello(){std::cout << "Hello world, I''m a thread!"<< std::endl;}static void start(){boost::thread thrd( hello );thrd.join();}};int main(int argc, char* argv[]){HelloWorld::start();  return 0;}在这里start()和hello()方法都必须是static方法。
(2)类内部非静态方法启动线程将hello成员函数,改为非静态函数。class HelloWorld{public:void hello(){std::cout << "Hello world, I''m a thread!"<< std::endl;}void start(){boost::thread thrd(boost::bind((&HelloWorld::hello,this));thrd.join();}};int main(int argc, char* argv[]){HelloWorld hl;       hl.start();return 0;}
第三种:用类内部函数在类外部创建线程class HelloWorld{public:void hello(const std::string& str){std::cout << str << std::endl;}};int main(int argc, char* argv[]){HelloWorld  hl;boost::thread thr_test(boost::bind((&HelloWorld::hello,hl,"test----"));      thr_test.detach();return 0;}
1 0
原创粉丝点击