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

93 lines
1.9 KiB
C++
Raw Normal View History

2020-03-26 17:35:12 +08:00
#include <chrono>
2017-09-24 14:01:30 +08:00
#include <iostream>
#include <string>
#include <thread>
#include "librf.h"
using namespace resumef;
//请打开结构化异常(/EHa)
auto async_signal_exception(const intptr_t dividend)
{
awaitable_t<int64_t> awaitable;
2017-09-24 14:01:30 +08:00
std::thread([dividend, awaitable]
2017-09-24 14:01:30 +08:00
{
2017-09-28 16:16:46 +08:00
std::this_thread::sleep_for(std::chrono::milliseconds(50));
2017-09-24 14:01:30 +08:00
try
{
2017-09-28 16:16:46 +08:00
//也可以注释掉这个判断,使用结构化异常。但就获得不了具体描述信息了
2017-09-24 14:01:30 +08:00
if (dividend == 0)
throw std::logic_error("divided by zero");
awaitable.set_value(10000 / dividend);
2017-09-24 14:01:30 +08:00
}
catch (...)
{
awaitable.set_exception(std::current_exception());
2017-09-24 14:01:30 +08:00
}
}).detach();
2018-03-27 00:34:31 +08:00
return awaitable.get_future();
2017-09-24 14:01:30 +08:00
}
2017-09-28 16:16:46 +08:00
auto async_signal_exception2(const intptr_t dividend)
{
awaitable_t<int64_t> awaitable;
2017-09-28 16:16:46 +08:00
std::thread([dividend, awaitable]
2017-09-28 16:16:46 +08:00
{
std::this_thread::sleep_for(std::chrono::milliseconds(50));
if (dividend == 0)
awaitable.throw_exception(std::logic_error("divided by zero"));
2017-09-28 16:16:46 +08:00
else
awaitable.set_value(10000 / dividend);
2017-09-28 16:16:46 +08:00
}).detach();
2018-03-27 00:34:31 +08:00
return awaitable.get_future();
2017-09-28 16:16:46 +08:00
}
future_t<> test_signal_exception()
2017-09-24 14:01:30 +08:00
{
for (intptr_t i = 10; i >= 0; --i)
{
#ifndef __clang__
2017-09-24 14:01:30 +08:00
try
#endif
2017-09-24 14:01:30 +08:00
{
2017-09-28 16:16:46 +08:00
auto r = co_await async_signal_exception2(i);
2017-09-24 14:01:30 +08:00
std::cout << "result is " << r << std::endl;
}
#ifndef __clang__
2017-09-24 14:01:30 +08:00
catch (const std::exception& e)
{
std::cout << "exception signal : " << e.what() << std::endl;
}
catch (...)
{
std::cout << "exception signal : who knows?" << std::endl;
}
#endif
2017-09-24 14:01:30 +08:00
}
}
future_t<> test_bomb_exception()
2017-09-24 14:01:30 +08:00
{
for (intptr_t i = 10; i >= 0; --i)
{
auto r = co_await async_signal_exception(i);
std::cout << "result is " << r << std::endl;
}
}
void resumable_main_exception()
{
go test_signal_exception();
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;
go test_bomb_exception();
2017-10-01 10:33:08 +08:00
this_scheduler()->run_until_notask();
2017-09-24 14:01:30 +08:00
}