基于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_mutex.cpp 908B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 
  2. #include <chrono>
  3. #include <iostream>
  4. #include <string>
  5. #include <conio.h>
  6. #include <thread>
  7. #include <deque>
  8. #include <mutex>
  9. #include "librf.h"
  10. using namespace resumef;
  11. mutex_t g_lock;
  12. std::deque<size_t> g_queue;
  13. future_vt test_mutex_pop(size_t idx)
  14. {
  15. using namespace std::chrono;
  16. for (size_t i = 0; i < 10; ++i)
  17. {
  18. co_await resumf_guard_lock(g_lock);
  19. if (g_queue.size() > 0)
  20. {
  21. size_t val = g_queue.front();
  22. g_queue.pop_front();
  23. std::cout << val << " on " << idx << std::endl;
  24. }
  25. co_await sleep_for(500ms);
  26. }
  27. }
  28. future_vt test_mutex_push()
  29. {
  30. using namespace std::chrono;
  31. for (size_t i = 0; i < 10; ++i)
  32. {
  33. co_await resumf_guard_lock(g_lock);
  34. g_queue.push_back(i);
  35. co_await sleep_for(500ms);
  36. }
  37. }
  38. void resumable_main_mutex()
  39. {
  40. go test_mutex_push();
  41. go test_mutex_pop(1);
  42. g_scheduler.run_until_notask();
  43. }