Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::thread c++. More threads same data

Im using visual studio 2012 and c++11. I dont understand why this does not work:

void client_loop(bool &run)
{
    while ( run );
}

int main()
{
    bool running = true;
    std::thread t(&client_loop,std::ref(running));

    running = false ;
    t.join();
}

In this case, the loop of thread t never finishes but I explicity set running to false. run and running have the same location. I tried to set running as a single global variable but nothing happens. I tried to pass a pointer value too but nothing.

The threads use the same heap. I really don't understand. Can anyone help me?

like image 549
Matteo Galeotti Avatar asked Mar 10 '13 23:03

Matteo Galeotti


1 Answers

Your program has Undefined Behavior, because it introduces a data race on the running variable (one thread writes it, another thread reads it).

You should use a mutex to synchronize access, or make running an atomic<bool>:

#include <iostream>
#include <thread>
#include <atomic>

void client_loop(std::atomic<bool> const& run)
{
    while (run.load());
}

int main()
{
    std::atomic<bool> running(true);
    std::thread t(&client_loop,std::ref(running));

    running = false ;
    t.join();

    std::cout << "Arrived";
}

See a working live example.

like image 96
Andy Prowl Avatar answered Oct 15 '22 12:10

Andy Prowl