Category : condition-variable

In this piece of code, where it is defined a class called Monitor that protects the data captured by a sensor: #include <iostream> #include <thread> #include <mutex> #include <condition_variable> #include <chrono> #include <cstdlib> #define SIZE_LOOP 1000 class Monitor { private: std::mutex m_mutex; std::condition_variable m_conditionVariable; bool m_isReady; public: Monitor() { init(); }; ~Monitor() { }; void ..

Read more

The following code shows is a struct I have written to allow me to queue up work to run on multiple worker threads, and which blocks the main thread until a new worker thread is available. struct WorkQueue{ const std::size_t size; std::vector<uint8_t> threadActive; std::condition_variable cond; std::mutex mu; std::vector<std::jthread> threads; WorkQueue(std::size_t size_ = 1) : size{size_} ..

Read more

Consider this: // Somewhere std::mutex mutex; std::unique_lock lock{mutex}; std::condition_variable condition; // Thread01 condition.wait(lock); // Thread02 while (lock.owns_lock()); So I got a situation like this where the loop at Thread02 never ends, regardless of the fact that Thread01 is waiting for the condition. This means that unlocking the lock at std::condition_variable::wait does not synchronize with checking ..

Read more

I use conditional_variable::notify_all() to wake up a waiting thread(only one thread is waiting for the unique_lock indeed). This code snippet works well at most time, but the log files(for details, see below) indicates that the parent thread could not aquire the unique_lock after the new created thread allready returned. I would be grateful to have ..

Read more

I have a worker thread in a thread pool that behaves like so: while (running) { std::unique_lock<std::mutex> lock(m_mutex); m_condition.wait(lock, [&] { return m_workAvailable; }); m_workAvailable = false; lock.unlock(); // (Perform work…) } When I drop work into this worker thread, it looks like so: // (enqueue the actual work item…) if (!m_workAvailable) { std::lock_guard<std::mutex> lock(m_mutex); ..

Read more

Recently I’m playing with std::thread and std::condition_variable but encountered something very confusing. There are two threads in my plan, one to submit tasks and another to execute them. Also, there are two kinds of std::condition_variable. One is used to notify the task thread that a new task has been added. And another one is for ..

Read more