c++ 多线程

发布时间 2023-08-19 09:42:08作者: Ultraman_X

#include <iostream>       
#include <functional>     
#include <thread>        
#include <future>     // std::promise, std::future
#include <chrono>

void print_int(std::future<int>& fut) {
    int x = fut.get();                    // 获取共享状态的值.
    std::cout << "value: " << x << '\n';  // 打印 value: 10.
}

int main()
{
    std::promise<int> prom;                    // 生成一个 std::promise<int> 对象.
    std::future<int> fut = prom.get_future();  // 和 future 关联.
    std::thread t(print_int, std::ref(fut));   // 将 future 交给另外一个线程t.
    
    std::this_thread::sleep_for(std::chrono::seconds(2));
    prom.set_value(10);                        // 设置共享状态的值, 此处和线程t保持同步.

    t.join();
    return 0;
}

得出promise里的值是异步的:
Calling future::get on a valid future blocks the thread until the provider makes the shared state ready (either by setting a value or an exception to it). This way, two threads can be synchronized by one waiting for the other to set a value.

线程池组成部分:

  • 线程池管理器(thread pool):创建、销毁线程池
  • 工作线程(pool wroker):在没有任务时处于等待状态,循环读取并执行任务队列中的任务
  • 任务(task):抽象一个任务,主要规定任务的入口、任务执行完后的收尾工作、任务的执行状态等
  • 任务队列(task queue):存放没有处理的任务,提供一种缓冲机制