基于C++ Coroutines提案 ‘Stackless Resumable Functions’编写的协程库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_async_exception.cpp 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <chrono>
  2. #include <iostream>
  3. #include <string>
  4. #include <thread>
  5. #include "librf/librf.h"
  6. using namespace librf;
  7. //请打开结构化异常(/EHa)
  8. auto async_signal_exception(const intptr_t dividend)
  9. {
  10. awaitable_t<int64_t> awaitable;
  11. std::thread([dividend, awaitable]
  12. {
  13. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14. try
  15. {
  16. //也可以注释掉这个判断,使用结构化异常。但就获得不了具体描述信息了
  17. if (dividend == 0)
  18. throw std::logic_error("divided by zero");
  19. awaitable.set_value(10000 / dividend);
  20. }
  21. catch (...)
  22. {
  23. awaitable.set_exception(std::current_exception());
  24. }
  25. }).detach();
  26. return awaitable.get_future();
  27. }
  28. auto async_signal_exception2(const intptr_t dividend)
  29. {
  30. awaitable_t<int64_t> awaitable;
  31. std::thread([dividend, awaitable]
  32. {
  33. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  34. if (dividend == 0)
  35. awaitable.throw_exception(std::logic_error("divided by zero"));
  36. else
  37. awaitable.set_value(10000 / dividend);
  38. }).detach();
  39. return awaitable.get_future();
  40. }
  41. future_t<> test_signal_exception()
  42. {
  43. for (intptr_t i = 10; i >= 0; --i)
  44. {
  45. try
  46. {
  47. auto r = co_await async_signal_exception2(i);
  48. std::cout << "result is " << r << std::endl;
  49. }
  50. catch (const std::exception& ex)
  51. {
  52. std::cout << "exception signal : " << ex.what() << std::endl;
  53. }
  54. catch (...)
  55. {
  56. std::cout << "exception signal : who knows?" << std::endl;
  57. }
  58. }
  59. }
  60. future_t<> test_bomb_exception()
  61. {
  62. for (intptr_t i = 10; i >= 0; --i)
  63. {
  64. auto r = co_await async_signal_exception(i);
  65. std::cout << "result is " << r << std::endl;
  66. }
  67. }
  68. void resumable_main_exception(bool bomb)
  69. {
  70. std::cout << __FUNCTION__ << std::endl;
  71. go test_signal_exception();
  72. this_scheduler()->run_until_notask();
  73. std::cout << std::endl;
  74. if (bomb)
  75. {
  76. go test_bomb_exception();
  77. this_scheduler()->run_until_notask();
  78. }
  79. }
  80. #if LIBRF_TUTORIAL_STAND_ALONE
  81. int main()
  82. {
  83. resumable_main_exception(true);
  84. return 0;
  85. }
  86. #endif