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

转自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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值