I have a simple class with a variable (var1). The function of the class "changeVar" will be passed to pthread which will update the value. My question is when that thread is called inside a child and it updates the value after the child exits why does the value go back to the default which is 0. And how can I keep the updated value in the parent process if there is a way to do so.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <iostream>
#include <random>
#include <ctime>
#include <sys/wait.h>
class my_class
{
public:
int var1;
my_class()
{
var1 = 0;
}
void* changeVar() //change variable function thread will start execution from this function
{
this->var1 = 1; //the thread will then update the value
}
void print_var() //function to simply print the var1 variabel.
{
std::cout << "The value of var 1 = " << this->var1 << std::endl;
}
};
int main()
{
typedef void* (*THREADFUNCPTR) (void* );
my_class* my_class_ptr = new my_class(); // creating pointer to class that I will send to the thread.
//forking a child;
if(fork() == 0)
{
pthread_t thread;
pthread_create(&thread, NULL, (THREADFUNCPTR) &my_class::changeVar, my_class_ptr); //creating thread
pthread_join(thread, NULL);
my_class_ptr->print_var(); //on this print call the value of var1 printed is 1
exit(0);
}
else
{
wait(NULL);
my_class_ptr->print_var(); //on this print call the value of var1 is 0
}
}