#include <iostream>
#include <thread>
#include <mutex>
#include <future>
#include <condition_variable>
std::mutex _mtx;
std::condition_variable _cv;
void task1(int a, int b, int& ret)
{
int ret_a = a * a;
int ret_b = b * 2;
std::unique_lock<std::mutex> lock(_mtx);
ret = ret_a + ret_b;
_cv.notify_one();
}
//子线程进行赋值,主线程进行获取
void task2(int a, int b, std::promise<int>& ret)
{
int ret_a = a * a;
int ret_b = b * 2;
ret.set_value(ret_a + ret_b);
}
//主线程进行赋值,子线程进行获取
void task3(int a,std::future<int>& b, std::promise<int>& ret)
{
int ret_a = a * a;
int ret_b = b.get() * 2;
ret.set_value(ret_a + ret_b);
}
//主线程进行赋值,子线程进行获取,多个子线程
//shared_future可多次get
void task4(int a, std::shared_future<int> b, std::promise<int> &ret)
{
int ret_a = a * a;
int ret_b = b.get() * 2;
ret.set_value(ret_a + ret_b);
}
//通过锁与条件变量进行赋值与获取
int main1()
{
int ret = 0;
std::thread t(task1,1,2, std::ref(ret));
//do something else
//
//
//get the return value
std::unique_lock<std::mutex>lock(_mtx);
_cv.wait(lock);
std::cout << "return value is " << ret << std::endl;
t.join();
}
//子线程进行赋值,主线程进行获取
int main2()
{
std::promise<int> p;
std::future<int> f = p.get_future();
std::thread t(task2, 1, 2, std::ref(p));
//do something else
//
//
//get the return value
std::cout << "return value is " << f.get() << std::endl;//get()只能进行一次
t.join();
}
//主线程进行赋值,子线程进行获取
int main3()
{
std::promise<int> p_ret;
std::future<int> f_ret = p_ret.get_future();
std::promise<int> p_in;
std::future<int> f_in = p_in.get_future();
std::thread t(task3, 1, std::ref(f_in), std::ref(p_ret));
//do something else
//
p_in.set_value(2);
//
//get the return value
std::cout << "return value is " << f_ret.get() << std::endl;//get()只能进行一次
t.join();
}
//主线程进行赋值,子线程进行获取
int main4()
{
std::promise<int> p_ret;
std::future<int> f_ret = p_ret.get_future();
std::promise<int> p_in;
std::future<int> f_in = p_in.get_future();
std::shared_future<int> s_f = f_in.share();
std::thread test1(task4, 1, s_f, std::ref(p_ret));
//std::thread test2(task4, 1, s_f, std::ref(p_ret));
//do something else
//
p_in.set_value(2);
//
//get the return value
std::cout << "return value is " << f_ret.get() << std::endl;//get()只能进行一次
test1.join();
//test2.join();
}
C++Promise和Future
最新推荐文章于 2024-09-03 11:25:36 发布