I have this code and I am not getting the expected results... whats wrong?
typedef struct {
int data1;
int data2;
}t;
void foo(int a, int b) {
Handle handle;
t arg;
arg.data1 = a;
arg.data2 = b;
handle = (HANDLE) _beginthread( myFunc, 0, (void*) &arg);
}
void myFunc(void *param) {
t *args = (t*) param;
int x = args->data1;
int y = args->data2;
printf("x=%d, y=%d\n", x, y);
}
your arg variable is a local variable in your function foo, so it will not be available in the memory after the function ends.
SO you can do two things:
1.define your arg variable globally.
or you can also allocate the memory for arg on help,as casablanca has explained.
Thanks Alok.Kr.
arg
is a local variable defined infoo
- it would be destroyed as soon as that function ends, butmyFunc
which is running in another thread would still be trying to access it. You should allocatearg
on the heap and destroy it in the thread after you are done.Also note that
HANDLE
should be all caps.