vendredi 5 janvier 2018

Synchronize two threads to the same timer

I have the following scenario:

int main(){
    data_t data;
    std::thread data_producer([&data](){
        while(true){
            data = produce_data();
            std::this_thread::sleep_for(1s);
        }
    }); 

    auto print_data = [&data](){
        std::cout << data.as_string() << "\n";
    });

    print_data();
    //do some stuff
    print_data();
    print_data();
    //do some stuff
    print_data();
    //.....
}

As you see, the data producer runs forever, trying to produce data and overwrite the old one each time.

When I call print_data(), the last produced data would be printed out. However, if print_data was faster than the data_producer, the same data will be printed twice.

How can I prevent this behavior? In other words, I want print_data() to be blocked until there is a new data from producer.

On the other hand, I do not mind if a data was produced and no one printed it. But I mind if the produced date was printed more than once?

I tried to use std::condition_variable with std::mutex. However, I could not came up with a solution.

How can I achieve this?

Aucun commentaire:

Enregistrer un commentaire