c++11 线程

转自:http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-3.html

是个just的c++库。和c11很像。

  • 用成员函数来作线程函数,需要传入额外的对象值。如果需要传入参数,接在头两个参数后面。
  • 用引用而不同拷贝对象,需要调用 std::ref
  • #include <thread>
    #include <iostream>
    
    class SayHello
    {
    public:
        void greeting(std::string const& message) const
        {
            std::cout<<message<<std::endl;
        }
    };
    
    int main()
    {
        SayHello x;
        std::thread t(&SayHello::greeting,&x,"goodbye");
        t.join();
    }
    

      

  • 栈上的对象,需要确保生命期比thread长。否则可以用  std::shared_ptr<SayHello> 确保对象存在,只要线程没死。
  • int main()
    {
        std::shared_ptr<SayHello> p(new SayHello);
        std::thread t(&SayHello::greeting,p,"goodbye");
        t.join();
    }
    

      

原文地址:https://www.cnblogs.com/bigben0123/p/3745027.html