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