wait_pred.pass.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // UNSUPPORTED: libcpp-has-no-threads
  10. // <condition_variable>
  11. // class condition_variable;
  12. // template <class Predicate>
  13. // void wait(unique_lock<mutex>& lock, Predicate pred);
  14. #include <condition_variable>
  15. #include <mutex>
  16. #include <thread>
  17. #include <functional>
  18. #include <cassert>
  19. #include "test_macros.h"
  20. std::condition_variable cv;
  21. std::mutex mut;
  22. int test1 = 0;
  23. int test2 = 0;
  24. class Pred
  25. {
  26. int& i_;
  27. public:
  28. explicit Pred(int& i) : i_(i) {}
  29. bool operator()() {return i_ != 0;}
  30. };
  31. void f()
  32. {
  33. std::unique_lock<std::mutex> lk(mut);
  34. assert(test2 == 0);
  35. test1 = 1;
  36. cv.notify_one();
  37. cv.wait(lk, Pred(test2));
  38. assert(test2 != 0);
  39. }
  40. int main(int, char**)
  41. {
  42. std::unique_lock<std::mutex>lk(mut);
  43. std::thread t(f);
  44. assert(test1 == 0);
  45. while (test1 == 0)
  46. cv.wait(lk);
  47. assert(test1 != 0);
  48. test2 = 1;
  49. lk.unlock();
  50. cv.notify_one();
  51. t.join();
  52. return 0;
  53. }