Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8825357
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T06:51:31+00:00 2026-06-14T06:51:31+00:00

I’m having some trouble understanding condition variables and their use with mutexes, I hope

  • 0

I’m having some trouble understanding condition variables and their use with mutexes, I hope the community can help me with. Please note, I come from a win32 background, so I’m used with CRITICAL_SECTION, HANDLE, SetEvent, WaitForMultipleObject, etc.

Here’s my first attempt at concurrency using the c++11 standard library, it’s a modified version of a program example found here.

#include <condition_variable>
#include <mutex>
#include <algorithm>
#include <thread>
#include <queue>
#include <chrono>
#include <iostream>


int _tmain(int argc, _TCHAR* argv[])
{   
    std::queue<unsigned int>    nNumbers;

    std::mutex                  mtxQueue;
    std::condition_variable     cvQueue;
    bool                        m_bQueueLocked = false;

    std::mutex                  mtxQuit;
    std::condition_variable     cvQuit;
    bool                        m_bQuit = false;


    std::thread thrQuit(
        [&]()
        {
            using namespace std;            

            this_thread::sleep_for(chrono::seconds(7));

            // set event by setting the bool variable to true
            // then notifying via the condition variable
            m_bQuit = true;
            cvQuit.notify_all();
        }
    );

    std::thread thrProducer(
        [&]()
        {           
            using namespace std;

            int nNum = 0;
            unique_lock<mutex> lock( mtxQuit );

            while( ( ! m_bQuit ) && 
                   ( cvQuit.wait_for( lock, chrono::milliseconds(10) ) == cv_status::timeout ) )
            {
                nNum ++;

                unique_lock<mutex> qLock(mtxQueue);
                cout << "Produced: " << nNum << "\n";
                nNumbers.push( nNum );              
            }
        }
    );

    std::thread thrConsumer(
        [&]()
        {
            using namespace std;            

            unique_lock<mutex> lock( mtxQuit );

            while( ( ! m_bQuit ) && 
                    ( cvQuit.wait_for( lock, chrono::milliseconds(10) ) == cv_status::timeout ) )
            {
                unique_lock<mutex> qLock(mtxQueue);
                if( nNumbers.size() > 0 )
                {
                    cout << "Consumed: " << nNumbers.front() << "\n";
                    nNumbers.pop();
                }               
            }
        }
    );

    thrQuit.join();
    thrProducer.join();
    thrConsumer.join();

    return 0;
}

A Few questions about this.

I’ve read that “any thread that intends to wait on std::condition_variable must acquire an std::unique_lock first.”

So I’ve got a {quit mutex, condition variable & bool} to indicate when quit has been signalled. The producer and consumer threads must each acquire an std::unique_lock as so:

std::unique_lock<std::mutex> lock(m_mtxQuit);

This is confusing the hell out of me. Won’t this lock the quit mutex in the first thread, thereby blocking the second? And if that’s true, then how does the first thread release the lock, so that the other thread can begin?

Another question: If I change the wait_for() call to wait for zero seconds, that thread is starved. Can someone explain? I’d expect it not to block before executing the while loop (am I correct to assume that a no_timeout is recv’d instead of a timeout?).

How can I call a wait_for() and specify a zero time, so that the wait_for() call doesn’t block, instead it just checks the condition and continues?

I’d also be interested to hear about good references on this subject.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T06:51:32+00:00Added an answer on June 14, 2026 at 6:51 am

    Won’t this lock the quit mutex in the first thread, thereby blocking the second?

    Yes.

    And if that’s true, then how does the first thread release the lock, so that the other thread can begin?

    When you wait on a condition_variable it unlocks the lock that you pass it, so in

    cvQuit.wait_for( lock, chrono::milliseconds(10) )
    

    the condition variable will call lock.unlock() and then block for up to 10ms (this happens atomically so there’s no window between unlocking the mutex and blocking where the condition could become ready and you’d miss it)

    When the mutex is unlocked it allows the other thread to acquire the lock on it.

    Another question: If I change the wait_for() call to wait for zero seconds, that thread is starved. Can someone explain?

    I would expect the other thread to be starved, because the mutex is not unlocked long enough for the other thread to lock it.

    am I correct to assume that a no_timeout is recv’d instead of a timeout?

    No, if the time duration passes without the condition becoming ready then it “times out” even after zero seconds.

    How can I call a wait_for() and specify a zero time, so that the wait_for() call doesn’t block, instead it just checks the condition and continues?

    Don’t use a condition variable! If you don’t want to wait for a condition to become true, don’t wait on a condition variable! Just test m_bQuit and proceed.
    (Aside, why are your booleans called m_bXxx? They’re not members, so the m_ prefix is misleading, and the b prefix looks like that awful MS habit of Hungarian notation … which stinks.)

    I’d also be interested to hear about good references on this subject.

    The best reference is Anthony Williams’s C++ Concurrency In Action which covers the entire C++11 atomics and thread libraries in detail, as well as the general principles of multithreading programming. One of my favourite books on the subject is Butenhof’s Programming with POSIX Threads, which is specific to Pthreads, but the C++11 facilities map very closely to Pthreads, so it’s easy to transfer the information from that book to C++11 multithreading.

    N.B. In thrQuit you write to m_bQuit without protecting it with a mutex, since nothing prevents another thread reading it at the same time as that write, it’s a race condition, i.e. undefined behaviour. The write to the bool must either be protected by a mutex or must be an atomic type, e.g. std::atomic<bool>

    I don’t think you need two mutexes, it just adds contention. Since you never release the mtxQuit except while waiting on the condition_variable there is no point having the second mutex, the mtxQuit one already ensures only one thread can enter the critical section at once.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is
I want use html5's new tag to play a wav file (currently only supported
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
Does anyone know how can I replace this 2 symbol below from the string

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.