Well I’m trying to set a variable to use in a thread, it works fine if I call the pthread from the main function, but if I call it from a function or a function inside a class, the variable is lost and prints garbage instead, that’s why I added the condition
if(this->pickup < 7)
so I minimized the code so I could post it here because it has all the examples I’m saying.
The output of this code below is:
Access by Class:
Hello, world! <
Access Directly:
Hello, world!, N: 6<
I would like to have the same result as in Access Directly in Access by Class, I want it to output the “, N: 6” because after all it was defined. what am I missing here?
I hope I was clear enough, thanks in advance.
(By the way, I’m using the pthread library that is available for windows)
so here is the code:
#include <stdio.h>
#include <pthread.h>
#include <iostream>
#include <conio.h>
#include <windows.h>
class C {
public:
int pickup;
void *hello()
{
std::cout << "\nHello, world!";
if(this->pickup < 7)
std::cout << ", N: " << this->pickup;
std::cout << "<" << std::endl;
printf("HI");
return 0;
}
static void *hello_helper(void *context)
{
return ((C *)context)->hello();
}
void StartThread(){
C c;
c.pickup = 6;
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);
}
};
int main () {
C c;
std::cout << "Access by Class: \n";
c.StartThread();
c.pickup = 6;
Sleep(2000);
std::cout << "\nAccess Directly: \n";
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);
_getch();
return 0;
}
cis destroyed whenStartThread()returns, meaninghello_helper()is using a dangling pointer resulting in undefined behaviour.Change to:
Remember to
deletethe argument passed intohello_helper():EDIT:
Always
deleteing the argument passed intohello_helper()would prevent passing stack allocated objects intohello_helper(). A mechanism is required to instructhello_helper()whether it is responsible for destructing its argument.