notify_all.pass.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. // void notify_all();
  13. #include <condition_variable>
  14. #include <mutex>
  15. #include <thread>
  16. #include <cassert>
  17. #include "test_macros.h"
  18. std::condition_variable cv;
  19. std::mutex mut;
  20. int test0 = 0;
  21. int test1 = 0;
  22. int test2 = 0;
  23. void f1()
  24. {
  25. std::unique_lock<std::mutex> lk(mut);
  26. assert(test1 == 0);
  27. while (test1 == 0)
  28. cv.wait(lk);
  29. assert(test1 == 1);
  30. test1 = 2;
  31. }
  32. void f2()
  33. {
  34. std::unique_lock<std::mutex> lk(mut);
  35. assert(test2 == 0);
  36. while (test2 == 0)
  37. cv.wait(lk);
  38. assert(test2 == 1);
  39. test2 = 2;
  40. }
  41. int main(int, char**)
  42. {
  43. std::thread t1(f1);
  44. std::thread t2(f2);
  45. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  46. {
  47. std::unique_lock<std::mutex>lk(mut);
  48. test1 = 1;
  49. test2 = 1;
  50. }
  51. cv.notify_all();
  52. {
  53. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  54. std::unique_lock<std::mutex>lk(mut);
  55. }
  56. t1.join();
  57. t2.join();
  58. assert(test1 == 2);
  59. assert(test2 == 2);
  60. return 0;
  61. }