基于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 914B

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