samedi 4 mai 2019

read variable value in main from thread in c++

I need to have a thread which executes a function in while loop(say increments an int value). In the main I need to have a while loop which executes some function(say a for loop which counts from 0 to 5) and then reads the current value of a variable in the thread. The thread must keep running its own while loop irrespective of whats going on in main. However the value of the thread variable must not change while main reads the variable.

I guess this problem can be solved using atomic. However this is a toy problem in which the variable in the thread is an int. In my actual problem the thread variable if of type Eigen::quaternionf or float[4]. So I need to ensure that the entire Eigen::quaternionf or float[4] is held constant when it is read from main.

The cout in the thread is only for debugging. If the code runs with thread safety, it can be removed. I read from another post that using cout in a thread safe manner may need to write a new wrapper around cout with a mutex. I want to avoid it.

My code fails(today is my first day with multithreading) and is as below along with observed output(selected parts). the code fails to keep the order of the output using cout(garbled output). Also I am not sure that the thread variable is correctly read by the main.

#include <thread>
#include <mutex>
#include <iostream>

int i = 0;


void safe_increment(std::mutex& i_mutex)
{

    while(1)
    {

    std::lock_guard<std::mutex> lock(i_mutex);
    ++i;

    std::cout << "thread: "<< std::this_thread::get_id() << ", i=" << i << '\n';
    }

}

int main()
{
    std::mutex i_mutex;  

    std::thread t1(safe_increment, std::ref(i_mutex));


   while(1)
{
    for(int k =0; k < 5; k++)
    {
    std::cout << "main: k =" << k << '\n';
    }

    std::lock_guard<std::mutex> lock(i_mutex);
    std::cout << "main: i=" << i << '\n';
}
}

The output(selected parts) I get is

thread: 139711042705152, i=223893
thread: 139711042705152, i=223894
thread: 139711042705152, i=223895
main: i=223895
main: k =0
thread: main: k =1139711042705152
main: k =2
main: k =3
, i=main: k =4
223896
thread: 139711042705152, i=223897
thread: 139711042705152, i=223898



thread: 139711042705152, i=224801
thread: 139711042705152, i=224802
main: i=224802
main: k =0
main: k =1
thread: main: k =2
main: k =3
main: k =4
139711042705152, i=224803
thread: 139711042705152, i=224804
thread: 139711042705152, i=224805

Aucun commentaire:

Enregistrer un commentaire