future、 promise 测试

main
parent 7f121cf0fc
commit 6e877a3bfe

@ -20,7 +20,8 @@ private:
public:
explicit SyncQueue(int maxSize)
: mMaxSize(maxSize) {
: mMaxSize(maxSize),
mStop(false) {
}
/**
@ -43,7 +44,6 @@ public:
if (mStop) return;
mQueue.push_back(std::forward<F>(f));
mNotEmpty.notify_all();
mNotEmpty.notify_all();
}

@ -60,7 +60,7 @@ private:
}
mThreadGroup.clear();
}
public:
ThreadPool(int numThreads = std::thread::hardware_concurrency(), int maxTask = 1000) :
mQueue(maxTask) {

@ -1,5 +1,6 @@
#include <iostream>
#include <thread>
#include <mutex>
std::mutex g_lock;
@ -256,25 +257,69 @@ void message_test() {
bus.SendReq<void, int &>(i);
bus.SendReq<void, const int &>(2);
bus.SendReq<void, int &&>(2);
}
#include <future>
void async_test() {
// promise 保有的是一个共享状态的值
std::promise<int> pr;
std::thread t([](std::promise<int> &p) {
p.set_value_at_thread_exit(9);
}, std::ref(pr));
std::future<int> f = pr.get_future();
auto res = f.get();
std::cout << "res : " << res << std::endl;
// packaged_task 保存的是一个函数
std::packaged_task<int(int)> task([](int a) {
return a + 7;
});
std::thread t1(std::ref(task), 1);
std::future<int> f1 = task.get_future();
auto r = f1.get();
std::cout << "r : " << r << std::endl;
std::packaged_task<int(int)> task1([](int a) {
return a + 7;
});
auto f2 = task1.get_future();
task1(3);
std::cout << "r2 : " << f2.get() << std::endl;
// std::launch::async 该种模式下立即创建线程
std::future<int> func1 = std::async(std::launch::async, []() {
return 8;
});
std::cout << "func1 : " << func1.get() << std::endl;
std::future<int> func2 = std::async(std::launch::deferred, []() {
return 8;
});
std::cout << "func2 : " << func2.get() << std::endl;
}
int main() {
// 线程测试
thread_test();
// 同步队列测试
//// 线程测试
// thread_test();
//// 同步队列测试
sync_test();
// 时间工具测试
chrono_test();
// 线程池测试
threadpool_test();
// AOP测试
aop_test();
// Any测试
any_test();
// IoC测试
ioc_test();
// 总线测试
message_test();
//// 时间工具测试
// chrono_test();
//// 线程池测试
// threadpool_test();
//// AOP测试
// aop_test();
//// Any测试
// any_test();
//// IoC测试
// ioc_test();
//// 总线测试
// message_test();
// 异步测试
// async_test();
return 0;
}
Loading…
Cancel
Save