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

82 lines
1.6 KiB
C++
Raw Normal View History

2020-03-26 17:26:39 +08:00
2017-09-24 14:01:30 +08:00
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include "librf.h"
using namespace resumef;
future_t<> test_sleep_use_timer()
2017-09-24 14:01:30 +08:00
{
using namespace std::chrono;
2020-03-17 23:40:39 +08:00
(void)sleep_for(100ms); //incorrect!!!
2018-08-10 06:02:01 +08:00
2020-03-17 23:40:39 +08:00
co_await sleep_for(100ms);
std::cout << "sleep_for 100ms." << std::endl;
co_await 100ms;
std::cout << "co_await 100ms." << std::endl;
2017-09-24 14:01:30 +08:00
2018-08-10 06:02:01 +08:00
try
{
2020-03-17 23:40:39 +08:00
co_await sleep_until(system_clock::now() + 200ms);
2017-09-24 14:01:30 +08:00
std::cout << "timer after 200ms." << std::endl;
2018-08-10 06:02:01 +08:00
}
2020-05-09 16:08:27 +08:00
catch (canceled_exception)
2018-08-10 06:02:01 +08:00
{
std::cout << "timer canceled." << std::endl;
}
2017-09-24 14:01:30 +08:00
}
void test_wait_all_events_with_signal_by_sleep()
{
using namespace std::chrono;
event_t evts[8];
go[&]() -> future_t<>
2017-09-24 14:01:30 +08:00
{
2020-04-18 11:46:29 +08:00
auto result = co_await event_t::wait_all(evts);
if (result)
2017-09-24 14:01:30 +08:00
std::cout << "all event signal!" << std::endl;
else
std::cout << "time out!" << std::endl;
};
srand((int)time(nullptr));
for (size_t i = 0; i < std::size(evts); ++i)
2017-09-24 14:01:30 +08:00
{
go[&, i]() -> future_t<>
2017-09-24 14:01:30 +08:00
{
2020-03-17 23:40:39 +08:00
co_await sleep_for(1ms * (500 + rand() % 1000));
2017-09-24 14:01:30 +08:00
evts[i].signal();
std::cout << "event[ " << i << " ] signal!" << std::endl;
};
}
2017-10-01 10:33:08 +08:00
while (!this_scheduler()->empty())
2017-09-24 14:01:30 +08:00
{
2017-10-01 10:33:08 +08:00
this_scheduler()->run_one_batch();
2017-09-24 14:01:30 +08:00
//std::cout << "press any key to continue." << std::endl;
//_getch();
}
}
void resumable_main_sleep()
{
go test_sleep_use_timer();
2017-10-01 10:33:08 +08:00
this_scheduler()->run_until_notask();
2017-09-24 14:01:30 +08:00
std::cout << std::endl;
test_wait_all_events_with_signal_by_sleep();
std::cout << std::endl;
}
2020-09-23 22:56:51 +08:00
int main()
{
resumable_main_sleep();
return 0;
}