C++11并发指南.01——std::thread


前言

C++11 新标准中引入了四个头文件来支持多线程编程,他们分别是atomic thread mutex condition_variable 和 future。

  • atomic:该头文主要声明了两个类, std::atomicstd::atomic_flag,另外还声明了一套 C 风格的原子类型和与 C 兼容的原子操作的函数。
  • thread:该头文件主要声明了 std::thread 类,另外 std::this_thread 命名空间也在该头文件中。
  • mutex:该头文件主要声明了与互斥量mutex相关的类,包括 std::mutex 系列类,std::lock_guard, std::unique_lock, 以及其他的类型和函数。
  • condition_variable:该头文件主要声明了与条件变量相关的类,包括 std::condition_variablestd::condition_variable_any
  • future:该头文件主要声明了 std::promise, std::package_task 两个 Provider 类,以及 std::futurestd::shared_future 两个 Future 类,另外还有一些与之相关的类型和函数,std::async() 函数就声明在此头文件中。

本文主要记录std::thread得用法详解等。


基础知识

  1. join是用来进行同步的一个工具,当我们在主进程中使用,join了一个子进程,那么主进程就要等待这个子进程运行完毕,并且回收子进程的资源后,再执行主进程的程序。如果一个线程没有joindetach在最后整个进程结束时,该回收的资源没有回收,则会产生错误。
  2. detach是将主线程和子线程进行分离,主线程是不会再等待子线程,主线程结束时,进程也就结束,但子线程会运行完,再被回收。
  3. swap函数参数为thread& x,即将线程对象的状态与x互换。
  4. joinable的意思是一个线程是否能够被执行joindetach操作,相同的线程只能join一次,也不能join完再进行detach,同理也不能被detach两次,所以joinable函数就是判断是否能被join或detach
    可被joinable的thread对象必须在销毁之前被主线程join或者将其设置为detached
    不能joinable的情况有:
    • 默认构造的,如std::thread t_1;
    • 执行过move操作
    • 执行过joindetach

std::thread 构造

name执行的操作解析
defaultthread() noexcept;默认构造函数,创建一个空的thread执行对象
initializationtemplate<class Fn, calss...Args>
explicit thread(Fn&& fn, Args&&... args);
初始化构造函数,创建一个thread对象,该对象可被joinable,新产生的线程会调用fn函数,该函数的参数由args给出
copy[delete]thread(const thread&) = delete;拷贝构造函数(被禁用)意味着thread不可被拷贝构造
movethread(thread&& x) noexcept;move构造函数,调用成功之后x不代表任何thread执行对象

各种构造含函数示例如下:

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
 
void f1(int n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread " << n << " executing\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}
 
void f2(int& n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread 2 executing\n";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}
 
int main()
{
    int n = 0;
    std::thread t1; // default, t1 is not a thread
    std::thread t2(f1, n + 1); // initialization, pass by value
    std::thread t3(f2, std::ref(n)); // pass by reference
    std::thread t4(std::move(t3)); // move, t4 is now running f2(). t3 is no longer a thread
    t2.join();
    t4.join();
    std::cout << "Final value of n is " << n << '\n';
}

move赋值操作

movethread& operator = (thread&& rhs) noexcpt;move赋值操作,如果当前对象不可joinable,需要传递一个右值引用(rhs)给move赋值操作;如果当前对象可被joinable,则terminate()报错。
copy[delete]thread& operator = (const thread&) = delete拷贝赋值操作被禁用,thread对象不可被拷贝

示例:

#include <stdio.h>
#include <stdlib.h>

#include <chrono>    // std::chrono::seconds
#include <iostream>  // std::cout
#include <thread>    // std::thread, std::this_thread::sleep_for

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";
    for (int i = 0; i < 5; i++) {
        threads[i] = std::thread(thread_task, i + 1);
    }
    std::cout << "Done spawning threads! Now wait for them to join\n";
    for (auto& t: threads) {
        t.join();
    }
    std::cout << "All threads joined.\n";

    return EXIT_SUCCESS;
}

其他成员函数

  • get_id
    获取线程ID
  • joinable
    检查线程是否可被join或detach
  • join
    join线程
  • detach
    detach线程
  • swap
    swap线程
  • native_handle
    返回 native handle
  • hardware_concurrency[static]
    检测硬件并发特性
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值