基于C++ Coroutines提案 ‘Stackless Resumable Functions’编写的协程库
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

test_async_exception.cpp 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. try
  47. {
  48. auto r = co_await async_signal_exception2(i);
  49. std::cout << "result is " << r << std::endl;
  50. }
  51. catch (const std::exception& e)
  52. {
  53. std::cout << "exception signal : " << e.what() << std::endl;
  54. }
  55. catch (...)
  56. {
  57. std::cout << "exception signal : who knows?" << std::endl;
  58. }
  59. }
  60. }
  61. future_t<> test_bomb_exception()
  62. {
  63. for (intptr_t i = 10; i >= 0; --i)
  64. {
  65. auto r = co_await async_signal_exception(i);
  66. std::cout << "result is " << r << std::endl;
  67. }
  68. }
  69. void resumable_main_exception()
  70. {
  71. go test_signal_exception();
  72. this_scheduler()->run_until_notask();
  73. std::cout << std::endl;
  74. go test_bomb_exception();
  75. this_scheduler()->run_until_notask();
  76. }