c++ 多线程
#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):存放没有处理的任务,提供一种缓冲机制
Fuature:
"Valid" futures are future objects associated to a shared state, and are constructed by calling one of the following functions:
- async
- promise::get_future
- packaged_task::get_future
Calling future::get on a valid future blocks the thread until the provider makes the shared state ready
async
例如:
std::future<bool> fut = std::async (is_prime,444444443);
promise::get_future
void print_int (std::future<int>& fut) {
int x = fut.get();
std::cout << "value: " << x << '\n';
}
int main ()
{
std::promise<int> prom; // create promise
std::future<int> fut = prom.get_future(); // engagement with future
std::thread th1 (print_int, std::ref(fut)); // send future to new thread
prom.set_value (10); // fulfill promise
// (synchronizes with getting the future)
th1.join();
return 0;
}
packaged_task::get_future:
int triple (int x) { return x*3; }
int main ()
{
std::packaged_task<int(int)> tsk (triple); // package task
std::future<int> fut = tsk.get_future(); // get future
std::thread(std::move(tsk),33).detach(); // spawn thread and call task
// ...
int value = fut.get(); // wait for the task to complete and get result
std::cout << "The triple of 33 is " << value << ".\n";
return 0;
}
posted on 2023-08-19 09:38 Ultraman_X 阅读(14) 评论(0) 编辑 收藏 举报