迁移(未编译通过)。
This commit is contained in:
60
task/main.cpp
Normal file
60
task/main.cpp
Normal file
@@ -0,0 +1,60 @@
|
||||
#include <future>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
// 1.Promise(生产者)和Future(消费者)
|
||||
void workTh1(std::promise<int> prom)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
prom.set_value(98);
|
||||
}
|
||||
|
||||
void testTaskTh1()
|
||||
{
|
||||
std::promise<int> prm;
|
||||
auto fut = prm.get_future();
|
||||
|
||||
std::thread t(workTh1, std::move(prm));
|
||||
|
||||
std::cout << "准备打印内容..." << std::endl;
|
||||
std::cout << fut.get() << std::endl;
|
||||
std::cout << "打印内容结束..." << std::endl;
|
||||
|
||||
t.join();
|
||||
}
|
||||
|
||||
// 2.std::packaged_task本质上是一个包装器, 包装可调用对象,内部使用了std::promise.
|
||||
int someFunc(int a, int b)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
return a + b;
|
||||
}
|
||||
|
||||
void testTaskTh2()
|
||||
{
|
||||
std::packaged_task<int(int, int)> pt(someFunc);
|
||||
auto fut = pt.get_future();
|
||||
std::thread t(std::move(pt), 33, 55);
|
||||
t.join();
|
||||
std::cout << __FUNCTION__ << " over, ret = " << fut.get() << std::endl;
|
||||
}
|
||||
|
||||
// 3.异步运行任务(更高级的用法,不用关心开线程打包这种操作)
|
||||
void testTaskTh3()
|
||||
{
|
||||
auto fut = std::async(std::launch::async, someFunc, 11, 22);
|
||||
std::cout << __FUNCTION__ << " over, ret = " << fut.get() << std::endl;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
#ifdef _WIN32
|
||||
SetConsoleOutputCP(CP_UTF8);
|
||||
#endif
|
||||
testTaskTh3();
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user