1
0
mirror of https://github.com/tearshark/librf.git synced 2024-10-01 15:57:07 +08:00
librf/tutorial/test_async_cb.cpp
tearshark 76811ba691 恢复新版本下的sleep功能
完善新版本下的部分测试用例
2020-02-16 01:18:25 +08:00

73 lines
1.6 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <chrono>
#include <iostream>
#include <string>
#include <conio.h>
#include <thread>
#include "librf.h"
template<class _Ctype>
void callback_get_long(int64_t val, _Ctype&& cb)
{
using namespace std::chrono;
std::thread([val, cb = std::forward<_Ctype>(cb)]
{
std::this_thread::sleep_for(500ms);
cb(val * val);
}).detach();
}
//这种情况下,没有生成 frame-context因此并没有promise_type被内嵌在frame-context里
auto async_get_long(int64_t val)
{
resumef::awaitable_t<int64_t> st;
callback_get_long(val, [st](int64_t val)
{
st.set_value(val);
});
return st.get_future();
}
resumef::future_t<> wait_get_long(int64_t val)
{
co_await async_get_long(val);
}
//这种情况下,会生成对应的 frame-context一个promise_type被内嵌在frame-context里
resumef::future_t<> resumable_get_long(int64_t val)
{
std::cout << val << std::endl;
val = co_await async_get_long(val);
std::cout << val << std::endl;
val = co_await async_get_long(val);
std::cout << val << std::endl;
val = co_await async_get_long(val);
std::cout << val << std::endl;
}
resumef::future_t<int64_t> loop_get_long(int64_t val)
{
std::cout << val << std::endl;
for (int i = 0; i < 5; ++i)
{
val = co_await async_get_long(val);
std::cout << val << std::endl;
}
co_return val;
}
void resumable_main_cb()
{
std::cout << std::this_thread::get_id() << std::endl;
GO
{
auto val = co_await loop_get_long(2);
std::cout << "GO:" << val << std::endl;
};
go resumable_get_long(3);
resumef::this_scheduler()->run_until_notask();
}