基于C++ Coroutines提案 ‘Stackless Resumable Functions’编写的协程库
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

test_async_exception.cpp 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. promise_t<int64_t> awaitable;
  13. std::thread([dividend, st = awaitable._state]
  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. st->set_value(10000 / dividend);
  22. }
  23. catch (...)
  24. {
  25. st->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. promise_t<int64_t> awaitable;
  33. std::thread([dividend, st = awaitable._state]
  34. {
  35. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  36. if (dividend == 0)
  37. st->throw_exception(std::logic_error("divided by zero"));
  38. else
  39. st->set_value(10000 / dividend);
  40. }).detach();
  41. return awaitable.get_future();
  42. }
  43. future_vt test_signal_exception()
  44. {
  45. for (intptr_t i = 10; i >= 0; --i)
  46. {
  47. try
  48. {
  49. auto r = co_await async_signal_exception2(i);
  50. std::cout << "result is " << r << std::endl;
  51. }
  52. catch (const std::exception& e)
  53. {
  54. std::cout << "exception signal : " << e.what() << std::endl;
  55. }
  56. catch (...)
  57. {
  58. std::cout << "exception signal : who knows?" << std::endl;
  59. }
  60. }
  61. }
  62. future_vt test_bomb_exception()
  63. {
  64. for (intptr_t i = 10; i >= 0; --i)
  65. {
  66. auto r = co_await async_signal_exception(i);
  67. std::cout << "result is " << r << std::endl;
  68. }
  69. }
  70. void resumable_main_exception()
  71. {
  72. go test_signal_exception();
  73. this_scheduler()->run_until_notask();
  74. std::cout << std::endl;
  75. go test_bomb_exception();
  76. this_scheduler()->run_until_notask();
  77. }