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

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