You are not logged in.

#1 2013-03-06 10:52:44

DarioP
Member
From: Geneva
Registered: 2011-01-05
Posts: 108

[solved]C++11 threads and condition variables - Can you execute this?

I am trying to run the example in this page http://en.cppreference.com/w/cpp/thread … n_variable you find it at the end of the post.
I am compling it with g++ 4.7.2 and everything goes fine, but when I run it I get:

$ g++ -std=c++11 -Wall test.cpp 
$ ./a.out 
terminate called after throwing an instance of 'std::system_error'
  what():  Operation not permitted
Cancelled (core dumped)

It's a bit strange because on http://liveworkspace.org/ with the same compiler it runs well. Could this be an Arch-related problem?


Source code:

#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>
#include <queue>
#include <chrono>
 
int main()
{
    std::queue<int> produced_nums;
    std::mutex m;
    std::condition_variable cond_var;
    bool done = false;
    bool notified = false;
 
    std::thread producer([&]() {
        for (int i = 0; i < 5; ++i) {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            std::unique_lock<std::mutex> lock(m);
            std::cout << "producing " << i << '\n';
            produced_nums.push(i);
            notified = true;
            cond_var.notify_one();
        }   
 
        notified = true;
        done = true;
        cond_var.notify_one();
    }); 
 
    std::thread consumer([&]() {
        std::unique_lock<std::mutex> lock(m);
        while (!done) {
            while (!notified) {  // loop to avoid spurious wakeups
                cond_var.wait(lock);
            }   
            while (!produced_nums.empty()) {
                std::cout << "consuming " << produced_nums.front() << '\n';
                produced_nums.pop();
            }   
            notified = false;
        }   
    }); 
 
    producer.join();
    consumer.join();
}

Last edited by DarioP (2013-03-06 12:04:16)

Offline

#2 2013-03-06 11:42:08

kaszak696
Member
Registered: 2009-05-26
Posts: 543

Re: [solved]C++11 threads and condition variables - Can you execute this?

g++ -std=c++11 -Wall -g -pthread test.cpp

'What can be asserted without evidence can also be dismissed without evidence.' - Christopher Hitchens
'There's no such thing as addiction, there's only things that you enjoy doing more than life.' - Doug Stanhope
GitHub Junkyard

Offline

#3 2013-03-06 11:47:31

DarioP
Member
From: Geneva
Registered: 2011-01-05
Posts: 108

Re: [solved]C++11 threads and condition variables - Can you execute this?

kaszak696 wrote:
-pthread

Pfff silly me yikes I lost a morning on this! And I even known that option!!!

That site should add the option automatically, that was confusing me hmm

Thank you very much wink

Offline

Board footer

Powered by FluxBB