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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. co_await resumf_guard_lock(g_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()
  27. {
  28. using namespace std::chrono;
  29. for (size_t i = 0; i < 10; ++i)
  30. {
  31. co_await resumf_guard_lock(g_lock);
  32. g_queue.push_back(i);
  33. co_await sleep_for(500ms);
  34. }
  35. }
  36. void resumable_main_mutex()
  37. {
  38. go test_mutex_push();
  39. go test_mutex_pop(1);
  40. this_scheduler()->run_until_notask();
  41. }