zoukankan      html  css  js  c++  java
  • c++并发编程之创建线程

    以boost为例。boost::thread有两个构造函数: 
    (1)thread():构造一个表示当前执行线程的线程对象; 
    (2)explicit thread(const boost::function0<void>& threadfunc): 
         boost::function0<void>可以简单看为:一个无返回(返回void),无参数的函数。这里的函数也可以是类重载operator()构成的函数;该构造函数传入的是函数对象而并非是函数指针,这样一个具有一般函数特性的类也能作为参数传入。

    方法1:通过无参数的函数创建线程

    #include <iostream>
    #include <boost/thread.hpp>
    
    void Hello() {
      // 睡眠一秒以模拟数据处理。
      boost::this_thread::sleep(boost::posix_time::seconds(1));
    
      std::cout << "Hello, World!" << std::endl;
    }
    
    int main() {
      // 创建一个线程对象,注意函数 Hello 将立即运行。
      boost::thread hello_thread(Hello);
    
      // 等待线程结束。
      // 否则线程还没执行(完),主程序就已经结束了。
      hello_thread.join();
    
      return 0;
    }

    方法2:通过带参数的函数创建线程

    #include <iostream>
    #include <boost/thread.hpp>
    
    void Hello(const char* what) {
      // 睡眠一秒以模拟数据处理。
      boost::this_thread::sleep(boost::posix_time::seconds(1));
    
      std::cout << "Hello, " << what << "!" << std::endl;
    }
    
    int main() {
      boost::thread hello_thread(Hello, "World");
      // 等价于使用 bind:
      // boost::thread hello_thread(boost::bind(&Hello, "World"));
    
      hello_thread.join();
    
      return 0;
    }

    方法3:通过一个函数对象,即仿函数(functor)创建线程

    #include <iostream>
    #include <boost/thread.hpp>
    
    class Hello {
    public:
      void operator()(const char* what) {
        boost::this_thread::sleep(boost::posix_time::seconds(1));
        std::cout << "Hello, " << what << "!" << std::endl;
      }
    };
    
    int main() {
      Hello hello;
    
      // 方式一:拷贝函数对象。
      boost::thread hello_thread(hello, "World");
      hello_thread.join();
    
      // 方式二:不拷贝函数对象,通过 boost::ref 传入引用。
      // 用户必须保证被线程引用的函数对象,拥有超出线程的生命期。
      // 比如这里通过 join 线程保证了这一点。 
      boost::thread hello_thread_ref(boost::ref(hello), "World");
      hello_thread_ref.join();
    
      return 0;
    }

    方法4:通过一个成员函数创建线程

    与前例不同之处在于,需要以 bind 绑定 this 指针作为第一个参数。

    #include <iostream>
    #include <boost/thread.hpp>
    
    class Hello {
    public:
      Hello() {
        boost::thread hello_thread(boost::bind(&Hello::Entry, this, "World"));
        hello_thread.join();
      }
    
    private:
      // 线程函数
      void Entry(const char* what) {
        boost::this_thread::sleep(boost::posix_time::seconds(1));
        std::cout << "Hello, " << what << "!" << std::endl;
      }
    };
    
    int main() {
      Hello hello;
      return 0;
    }

    tip: 关于thread::join() 和thread::detach(), 参见https://www.cnblogs.com/zhanghu52030/p/9166526.html 

  • 相关阅读:
    部分测试文档
    部分说明文档
    最终复审
    M2postmortem
    Beta版本发布说明
    M2项目测试
    Daily scrum 12.24
    Daily scrum 12.21
    Daily scrum 12.20
    个人阅读作业2
  • 原文地址:https://www.cnblogs.com/zhanghu52030/p/9166434.html
Copyright © 2011-2022 走看看