passing arguments to _beginthread() — whats wrong?

2019-04-30 04:27发布

问题:

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);
} 

回答1:

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.



回答2:

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.