C++11并发/多线程编程系列(2)

来源:互联网 发布:mac在哪里新建文件夹 编辑:程序博客网 时间:2024/06/14 05:10

转自http://www.cnblogs.com/haippy/p/3236136.html

std::thread详解

std::thread在头文件<thread>中声明,因此使用 std::thread 时需要包含 <thread>头文件。

default(1) thread() noexcept; initialization (2) template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&… args); copy [deleted] (3) thread (const thread&) = delete; move (4) thread (thread&& x) noexcept;


  • (1). 默认构造函数,创建一个空的 thread 执行对象。

  • (2). 初始化构造函数,创建一个 thread对象,该 thread对象可被 joinable新产生的线程会调用 fn 函数,该函数的参数由 args 给出

  • (3). 拷贝构造函数(被禁用),意味着 thread 不可被拷贝构造

  • (4). move 构造函数,move 构造函数,调用成功之后 x 不代表任何 thread 执行对象。

注意:可被 joinable 的 thread 对象必须在他们销毁之前被主线程 join 或者将其设置为 detached.

主线程中执行joinable对象的join(),相当于在主线程中添加这些thread,也就是在这些添加的thread执行完毕之后才会继续执行主线程,类似嵌入代码

join进入主线程的thread并不是从头执行,而是继续执行到完毕,或者说主线程等待其执行到完毕。相当于异步执行变为了同步执行。


move操作

move: thread& operator= (thread&& rhs) noexcept;

  • thread类中的operator=是move操作,不是copy操作

  • 将rhs这个thread对象的状态赋值到*this中

    thread object whose state is moved to *this.

  • move 赋值操作,如果当前对象不可 joinable,需要传递一个右值引用(rhs)给 move 赋值操作;

  • 如果当前对象可被 joinable,则 terminate() 被调用。

例子如下:

#include <stdio.h>#include <stdlib.h>#include <chrono>    // std::chrono::seconds#include <iostream>  // std::cout#include <thread>    // std::thread, std::this_thread::sleep_for// thread运行函数void thread_task(int n) {    std::this_thread::sleep_for(std::chrono::seconds(n));    std::cout << "hello thread "        << std::this_thread::get_id()        << " paused " << n << " seconds" << std::endl;}int main(int argc, const char *argv[]){    std::thread threads[5];    std::cout << "Spawning 5 threads...\n";    // 创建5个线程    for (int i = 0; i < 5; i++) {        // move-assign threads        threads[i] = std::thread(thread_task, i + 1);    }    std::cout << "Done spawning threads! Now wait for them to join\n";    // 5个线程依次join()    for (auto& t: threads) {        t.join();    }    std::cout << "All threads joined.\n";    return 0;} 

还有一些其余的常规函数,可以查阅手册
std::thread

0 0
原创粉丝点击