Skip to content

Instantly share code, notes, and snippets.

@Shaun289
Created April 1, 2022 09:13
Show Gist options
  • Save Shaun289/976f9c6f326c9a4506a84f874ed43faa to your computer and use it in GitHub Desktop.
Save Shaun289/976f9c6f326c9a4506a84f874ed43faa to your computer and use it in GitHub Desktop.
c++11 condition_variable test
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
/// compile : g++ -std=c++11 -pthread cv_test.cpp -o cv_test && ./cv_test
std::condition_variable _cv;
std::mutex _mutex;
int32_t _value;
int32_t _running;
void provider()
{
_running = true;
while (_running) {
{
std::lock_guard<std::mutex> lock(_mutex);
_value++;
}
_cv.notify_one();
printf("%s %4d %s : notify value:%d\n", __FILE__, __LINE__, __func__, _value);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
printf("%s %4d %s : out\n", __FILE__, __LINE__, __func__);
}
void consumer()
{
_running = true;
while (_running) {
std::unique_lock<std::mutex> lock(_mutex);
_cv.wait(lock, []() -> bool {
bool b = !_running || _value >= 10;
printf("%s %4d %s : running:%d value:%d return:%d\n", __FILE__, __LINE__, __func__, _running, _value, b);
return b;
});
printf("%s %4d %s : running:%d value:%d out\n", __FILE__, __LINE__, __func__, _running, _value);
_value = 0;
}
printf("%s %4d %s : out\n", __FILE__, __LINE__, __func__);
}
int main(int argc, char* argv[])
{
std::thread provider_th(provider);
std::thread consumer_th(consumer);
std::this_thread::sleep_for(std::chrono::seconds(10));
_running = false;
_cv.notify_all();
provider_th.join();
consumer_th.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment