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

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