I have an issue with multithreading where I probably lack understanding. I want to assign a member variable of an object inside a thread and then print the variable from another thread (or main in this case). It seems like I am doing something wrong, like there are two objects.
Here is a quick example:
thread_test.hpp
#pragma once
#include <iostream>
#include <chrono>
#include <thread>
class thread_test
{
public:
thread_test ():
test_variable{}
{}
int get_test_variable() const;
void updater_method();
private:
/* private data */
int test_variable;
};
thread_test.cpp
#include "thread_test.hpp"
void thread_test::updater_method()
{
int i{};
while(true)
{
test_variable = ++i;
std::this_thread::sleep_for(std::chrono::microseconds{1800});
}
}
int thread_test::get_test_variable() const
{
return test_variable;
}
main.cpp
#include <iostream>
#include <thread>
#include <unistd.h>
#include "thread_test.hpp"
int main()
{
thread_test obj{};
std::thread updater_thread(&thread_test::updater_method, obj);
while(true)
{
std::cout << obj.get_test_variable() << std::endl;
sleep(1);
}
return 0;
}
Output:
❯ ./main
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
I don't understand why the variable stays at the initialized value, because I am assigning it in the thread for the test object. Is there a better way to start the thread or should I start the thread from the class itself? What is the right way to do this?