zengine-old/engine/3rdparty/zlib/test/02condition.cpp

56 lines
1.4 KiB
C++
Raw Permalink Normal View History

2024-02-07 16:24:11 +08:00
#include <iostream>
#include <condition_variable>
#include <thread>
#include <queue>
using namespace std;
#define LOOP_TIMES 50
void test1() {
int res = 0, fake_count = 0;
mutex mtx;
condition_variable cv;
queue<int> mq;
thread t1([&]() {
for (int i = 0; i < LOOP_TIMES * 2; i++) {
this_thread::sleep_for(chrono::milliseconds(i));
//unique_lock<mutex> lock(mtx);
mq.push(i / 4);
//std::cout << "notify one " << i << " " << res << "\n";
cv.notify_all();
res = res + 1;
}
});
auto consume_fn = [&]() {
for (int i = 0; i < LOOP_TIMES; i++) {
this_thread::sleep_for(chrono::milliseconds(i));
unique_lock<mutex> lock(mtx);
while (mq.empty()) {
fake_count++;
//std::cout << "wait one " << i << " " << res << " " << fake_count << "\n";
cv.wait(lock);
}
//std::cout << "handle one " << i << " " << res << "\n";
mq.pop();
}
};
thread t2(consume_fn);
thread t3(consume_fn);
t1.join();
t2.join();
t3.join();
std::cout << "test3:: res:: " << res << " fake_count:: " << fake_count << " condition_variable:: size " << sizeof(cv) << endl;
}
int main() {
test1();
/*
wait(unique_lock<mutex>);
unlock
wait cond 线
lock
notify_one 线
线
*/
return 1;
}