1 /* 2 * Copyright (C) 2015-2019 Alibaba Group Holding Limited 3 */ 4 5 #include <posix/timer.h> 6 7 #include <condition_variable> 8 #include <iostream> 9 #include <mutex> 10 #include <thread> 11 12 using namespace std; 13 14 #define TEST_COUNT 10 15 static bool data_ready = false; 16 static int critical_resource = 0; 17 18 std::mutex _mutex; 19 std::condition_variable cond_var; 20 task0_entry(void)21static void task0_entry(void) 22 { 23 int i; 24 std::unique_lock<std::mutex> lck(_mutex, std::defer_lock); 25 26 for (i = 0; i < TEST_COUNT; i++) { 27 lck.lock(); 28 while (data_ready == false) { 29 cond_var.wait(lck); 30 } 31 critical_resource--; 32 cout << "access the resource through a condition variable" << endl; 33 if (critical_resource != 0) { 34 cout << "condition varialbe test error" << endl; 35 } 36 data_ready = false; 37 lck.unlock(); 38 } 39 } 40 task1_entry(void)41static void task1_entry(void) 42 { 43 int i; 44 std::unique_lock<std::mutex> lck(_mutex, std::defer_lock); 45 46 for (i = 0; i < TEST_COUNT; i++) { 47 lck.lock(); 48 data_ready = true; 49 critical_resource++; 50 cond_var.notify_one(); 51 lck.unlock(); 52 sleep(1); 53 } 54 } 55 conditon_varialbe_test(void)56void conditon_varialbe_test(void) 57 { 58 cout << "conditon varialbe test start" << endl; 59 thread thread0(task0_entry); 60 thread thread1(task1_entry); 61 thread0.join(); 62 thread1.join(); 63 cout << "conditon varialbe test ok" << endl; 64 } 65