1
0
mirror of https://github.com/tearshark/librf.git synced 2024-10-02 00:00:11 +08:00
librf/tutorial/test_async_event_v2.cpp

112 lines
2.3 KiB
C++
Raw Normal View History

2020-03-26 17:35:12 +08:00
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include "librf.h"
using namespace resumef;
2020-03-10 22:34:50 +08:00
using namespace std::chrono;
//非协程的逻辑线程或异步代码可以通过event_t通知到协程并且不会阻塞协程所在的线程。
2020-03-10 21:31:05 +08:00
static std::thread async_set_event_all(const event_v2::event_t & e, std::chrono::milliseconds dt)
{
return std::thread([=]
{
std::this_thread::sleep_for(dt);
2020-03-10 21:31:05 +08:00
e.signal_all();
});
}
2020-03-10 21:31:05 +08:00
static std::thread async_set_event_one(event_v2::event_t e, std::chrono::milliseconds dt)
{
return std::thread([=]
{
std::this_thread::sleep_for(dt);
2020-03-10 21:31:05 +08:00
e.signal();
});
}
2020-03-10 21:31:05 +08:00
static future_t<> resumable_wait_event(event_v2::event_t e, int idx)
{
2020-03-10 21:31:05 +08:00
if (co_await e)
std::cout << "[" << idx << "]event signal!" << std::endl;
else
2020-03-10 22:34:50 +08:00
std::cout << "[" << idx << "]time out!" << std::endl;
}
2020-03-10 22:34:50 +08:00
static future_t<> resumable_wait_timeout(event_v2::event_t e, milliseconds dt, int idx)
{
2020-03-10 22:34:50 +08:00
if (co_await e.wait_for(dt))
std::cout << "[" << idx << "]event signal!" << std::endl;
else
std::cout << "[" << idx << "]time out!" << std::endl;
}
2020-03-10 22:34:50 +08:00
static void test_notify_all()
{
event_v2::event_t evt;
go resumable_wait_event(evt, 0);
go resumable_wait_event(evt, 1);
go resumable_wait_event(evt, 2);
2020-03-10 22:34:50 +08:00
auto tt = async_set_event_all(evt, 100ms);
this_scheduler()->run_until_notask();
2020-03-10 22:34:50 +08:00
tt.join();
}
2020-03-10 21:31:05 +08:00
static void test_notify_one()
{
using namespace std::chrono;
{
event_v2::event_t evt;
go resumable_wait_event(evt, 10);
go resumable_wait_event(evt, 11);
go resumable_wait_event(evt, 12);
auto tt1 = async_set_event_one(evt, 100ms);
auto tt2 = async_set_event_one(evt, 500ms);
auto tt3 = async_set_event_one(evt, 800ms);
this_scheduler()->run_until_notask();
tt1.join();
tt2.join();
tt3.join();
}
}
2020-03-10 22:34:50 +08:00
static void test_wait_all_timeout()
{
using namespace std::chrono;
srand((int)time(nullptr));
event_v2::event_t evts[10];
std::vector<std::thread> vtt;
for(size_t i = 0; i < _countof(evts); ++i)
{
go resumable_wait_timeout(evts[i], 100ms, (int)i);
vtt.emplace_back(async_set_event_one(evts[i], 1ms * (50 + i * 10)));
}
this_scheduler()->run_until_notask();
for (auto& tt : vtt)
tt.join();
}
void resumable_main_event_v2()
{
test_notify_all();
std::cout << std::endl;
test_notify_one();
std::cout << std::endl;
2020-03-10 22:34:50 +08:00
test_wait_all_timeout();
std::cout << std::endl;
}