Condition variables | Simple producer consumer question

Hello guys,
I'm having a look at some easy concurrent programming in C++ atm and having trouble putting condition variables into use.
I have written a simple program with a global queue in which 2 threads are pushing numbers: one thread only pushes 1's, another only 2's.

Now I want to notify my main thread whenever a value is available to get read and simply print them out.

However, when running my code I always get the following exception thrown:
"terminate called after throwing and instance of 'std::system_error'
what(): Operation not permitted"
after a single 1 and a 2 got printed out.

Could someone explain to me what I am getting wrong?
Thank you very much :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
std::queue<int> q;
std::mutex m;
std::condition_variable c;
bool one_finished = false;
bool two_finished = false;

void produceOnes(){
    for(int i = 0; i < 5; i++){
        std::unique_lock<std::mutex> lock(m);
        q.push(1);
        lock.unlock();

        c.notify_all();

        std::this_thread::sleep_for(std::chrono::milliseconds(300));
    }
    one_finished = true;
}

void produceTwos(){
    for(int i = 0; i < 5; i++){
        std::unique_lock<std::mutex> lock(m);
        q.push(2);
        lock.unlock();

        c.notify_all();

        std::this_thread::sleep_for(std::chrono::milliseconds(300));
        }
        two_finished = true;
}


int main(){
    std::unique_lock<std::mutex> lock(m);

    std::thread t1(produceOnes);
    std::thread t2(produceTwos);

    while(!(one_finished && two_finished)){
        c.wait(lock, []{return !q.empty();});
        std::cout << q.front() << std::endl;
        q.pop();
        lock.unlock();
    }

    t1.join();
    t2.join();
}
Last edited on
Topic archived. No new replies allowed.