C++ 多线程(二)
一些简单临时的异步任务可以使用async创建,对应需要将任务放到线程池或者自己管理的线程中则可以使用packaged_task。当使用async时,传入launch::async是执行在子线程,而若使用launch::deferred 是执行在主线程。同理的还有try_lock_for、try_lock_until 以及 wait_for、wait_until。sleep_for 是睡眠多少时间,
·
C++ 多线程(二)
一、获取其他线程的计算结果(async 和 future)
string Func01(int a)
{
cout << a << endl;
this_thread::sleep_for(chrono::seconds(5));
return "Hello World";
}
future<string> data = async(launch::async, Func01, 100);
cout << data.get() << endl;
cout << "End" << endl;
当使用async时,传入launch::async是执行在子线程,而若使用launch::deferred 是执行在主线程。
当我们get时若子线程执行完毕则获取结果,若子线程没有执行完毕则阻塞等待执行完后返回结果。
二、主线程如何将数据发送到其他的线程(promise)
void Func02(future<string> a)
{
this_thread::sleep_for(chrono::seconds(2));
cout << a.get() << endl;
}
promise<string> pro;
future<string> fu = pro.get_future();
auto result = async(launch::async, Func02, move(fu));
pro.set_value("Hello!!!");
result.wait();
可能产生一个疑问,这样传递数值到子线程中和我们thread构造的时候传入参数有什么区别呢?
三、多线程之间如何共享状态(shared_future)
void Func03(shared_future<string> a)
{
this_thread::sleep_for(chrono::seconds(2));
cout << "Func03:" << a.get() << endl;
}
void Func04(shared_future<string> a)
{
this_thread::sleep_for(chrono::seconds(2));
cout << "Func04:" << a.get() << endl;
}
void Func05(shared_future<string> a)
{
this_thread::sleep_for(chrono::seconds(2));
cout << "Func05:" << a.get() << endl;
}
promise<string> pro1;
future<string> fu1 = pro1.get_future();
shared_future<string> shareFu = fu1.share();
auto a1 = async(launch::async, Func03, shareFu);
auto a2 = async(launch::async, Func04, shareFu);
auto a3 = async(launch::async, Func05, shareFu);
pro1.set_value("Test!!!");
a1.wait();
a2.wait();
a3.wait();
当我们需要一个参数共享到不同的线程任务中时可以使用shared_future这种方式来实现
最终输出:
同时输出
四、packaged_task
packaged_task<int(int, int)> task([](int a,int b)->int
{
this_thread::sleep_for(chrono::seconds(2));
cout << a + b << endl;
return a + b;
});
future<int> f = task.get_future();
thread t(move(task), 1, 2);
t.detach();
cout << "Do other !!!" << endl;
cout << f.get() << endl;
这种异步任务和之前的async有什么区别呢?
一些简单临时的异步任务可以使用async创建,对应需要将任务放到线程池或者自己管理的线程中则可以使用packaged_task
五、时间约束
sleep_for 是睡眠多少时间,而sleep_until 是睡眠到某一时间点
同理的还有try_lock_for、try_lock_until 以及 wait_for、wait_until
以下是代码:
this_thread::sleep_for(chrono::seconds(10));
chrono::steady_clock::time_point timePos = chrono::steady_clock::now() + chrono::seconds(5);
this_thread::sleep_until(timePos);
cout << "5s End" << endl;
mutex mt;
unique_lock<mutex> l(mt);
l.try_lock_for(chrono::seconds(2));
l.try_lock_until(chrono::steady_clock::now() + chrono::seconds(5));
promise<int> Pro;
future<int> Fu = Pro.get_future();
Fu.wait_for(chrono::seconds(2));
Fu.wait_until(chrono::steady_clock::now() + chrono::seconds(5));
condition_variable cv;
cv.wait_for(l, chrono::seconds(2));
cv.wait_until(l, chrono::steady_clock::now() + chrono::seconds(5));
更多推荐
所有评论(0)