基于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 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <chrono>
  2. #include <iostream>
  3. #include <string>
  4. #include <thread>
  5. #include "librf.h"
  6. using namespace resumef;
  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. #ifndef __clang__
  46. try
  47. #endif
  48. {
  49. auto r = co_await async_signal_exception2(i);
  50. std::cout << "result is " << r << std::endl;
  51. }
  52. #ifndef __clang__
  53. catch (const std::exception& e)
  54. {
  55. std::cout << "exception signal : " << e.what() << std::endl;
  56. }
  57. catch (...)
  58. {
  59. std::cout << "exception signal : who knows?" << std::endl;
  60. }
  61. #endif
  62. }
  63. }
  64. future_t<> test_bomb_exception()
  65. {
  66. for (intptr_t i = 10; i >= 0; --i)
  67. {
  68. auto r = co_await async_signal_exception(i);
  69. std::cout << "result is " << r << std::endl;
  70. }
  71. }
  72. void resumable_main_exception()
  73. {
  74. go test_signal_exception();
  75. this_scheduler()->run_until_notask();
  76. std::cout << std::endl;
  77. go test_bomb_exception();
  78. this_scheduler()->run_until_notask();
  79. }