views:

39

answers:

2

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);
} 
+2  A: 

arg is a local variable defined in foo - it would be destroyed as soon as that function ends, but myFunc which is running in another thread would still be trying to access it. You should allocate arg on the heap and destroy it in the thread after you are done.

void foo(int a, int b) {
   HANDLE handle;
   t *arg;
   arg = (t *)malloc(sizeof(t));
   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);
   free(args);
}

Also note that HANDLE should be all caps.

casablanca
thanks, I don't know how I didn't realize that at the time
emge
@ Casablanca , I think you made a typo.handle = (HANDLE) _beginthread( myFunc, 0, (void*) args); /// its argThanksAlok.kr.
Kumar Alok
Thanks for pointing that out, I've corrected it now.
casablanca
A: 

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.

typedef struct {
   int data1;
   int data2;
}t;
t arg;

or you can also allocate the memory for arg on help,as casablanca has explained.

Thanks Alok.Kr.

Kumar Alok