passing arguments to _beginthread() -- whats wrong?

10,056

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.

Share:
10,056
emge
Author by

emge

Updated on June 04, 2022

Comments

  • emge
    emge about 2 years

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