Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing arguments to _beginthread() -- whats wrong?

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);
} 
like image 694
emge Avatar asked Jul 02 '10 20:07

emge


1 Answers

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.

like image 92
casablanca Avatar answered Sep 20 '22 02:09

casablanca