c++11 线程
时间:2014-05-27 00:09:06
收藏:0
阅读:335
转自:http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-3.html
是个just的c++库。和c11很像。
- 用成员函数来作线程函数,需要传入额外的对象值。如果需要传入参数,接在头两个参数后面。
- 用引用而不同拷贝对象,需要调用 std::ref
-
123456789101112131415161718
#include <thread>#include <iostream>classSayHello{public:voidgreeting(std::stringconst& message)const{std::cout<<message<<std::endl;}};intmain(){SayHello x;std::threadt(&SayHello::greeting,&x,"goodbye");t.join();} -
栈上的对象,需要确保生命期比thread长。否则可以用 std::shared_ptr<SayHello> 确保对象存在,只要线程没死。 -
123456
intmain(){std::shared_ptr<SayHello> p(newSayHello);std::threadt(&SayHello::greeting,p,"goodbye");t.join();}
评论(0)