coroution.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #pragma once
  2. #if 0
  3. #include <coroutine>
  4. #include <iostream>
  5. #include <thread>
  6. #include <chrono>
  7. #include "util/thread.h"
  8. #include "util/queue.hpp"
  9. class co_thread_pool;
  10. namespace ylib::co
  11. {
  12. class coroutine {
  13. public:
  14. struct promise_type {
  15. coroutine get_return_object() {
  16. return coroutine{ std::coroutine_handle<promise_type>::from_promise(*this) };
  17. }
  18. std::suspend_always initial_suspend() { return {}; } // 协程初始化时挂起
  19. std::suspend_never final_suspend() noexcept { return {}; } // 协程结束时挂起
  20. void return_void() {}
  21. void unhandled_exception() { std::exit(1); }
  22. };
  23. coroutine(std::coroutine_handle<promise_type> h) : coro(h) {}
  24. ~coroutine() { if (coro) coro.destroy(); }
  25. std::coroutine_handle<promise_type> coro;
  26. };
  27. /// <summary>
  28. /// 协程调度器
  29. /// </summary>
  30. class scheduler :public ylib::ithread {
  31. public:
  32. // 任务信息
  33. struct task_info {
  34. // 任务回调
  35. std::function<void(void*,ylib::co::scheduler*)> callback;
  36. // 任务参数
  37. void* param = nullptr;
  38. // 唤醒协程coco
  39. std::coroutine_handle<>* coco = nullptr;
  40. };
  41. public:
  42. scheduler();
  43. ~scheduler();
  44. /// <summary>
  45. /// 启动
  46. /// </summary>
  47. /// <param name="thread_size">挂起协程执行任务线程池大小</param>
  48. /// <returns></returns>
  49. bool start(uint32 thread_size);
  50. void stop();
  51. /// <summary>
  52. /// 投递协程
  53. /// </summary>
  54. /// <param name="info"></param>
  55. void push(const task_info& info);
  56. /// <summary>
  57. /// 投递线程任务
  58. /// </summary>
  59. /// <param name="callback"></param>
  60. void push_t(std::function<void()> callback);
  61. /// <summary>
  62. /// 唤醒协程
  63. /// </summary>
  64. /// <param name="continuation"></param>
  65. void resume(std::coroutine_handle<>* continuation);
  66. private:
  67. // 通过 ithread 继承
  68. bool run() override;
  69. /// <summary>
  70. /// 处理队列
  71. /// </summary>
  72. void exec_queue();
  73. private:
  74. // 协程处理队列
  75. ylib::queue<task_info> m_queue;
  76. // 线程池
  77. co_thread_pool* m_pool = nullptr;
  78. };
  79. }
  80. #endif