简体   繁体   中英

Posix Pthread in C

I have the following questions regarding pthread of posix.

  • When we receive data in pthread_join() returned by the function being executed by a thread, we type cast the variable like (void **) even though the variable is a single pointer.

     int *x; pthread_join(tid,(void**)&x); printf("%d",*x); 
  • Should I derefrence the type casted argument (in case of structure)? Why can't I do like struct Data *obj= & (struct Data*)arg; ?

     int main() { ... pthread_create(tid,NULL,Foo,&obj); ... } void *Foo(void *arg) { struct Data *obj=* (struct Data*)arg; } 
  • How does pthread_join() internally receives the returned variable.

Regards

First of, you should never do (void**)&x as pointers off different types need not be of the same size.

Now, some scenarios (some valid, some working but invalid and some just broken):

Foo() returning a pointer to an int (valid) :

void* Foo(void *arg)
{
    int *ret = malloc(sizeof(int));
    *ret = 42;
    return ret;
}

void *ptr;
int *x;
pthread_join(thread, &ptr);
x = ptr;
printf("%d", *x);
free(x);

Foo() returning an int (invalid but usually work):
Platforms where int is larger than a pointer this will not work.

void* Foo(void *arg)
{
   return 42;
}

void *ptr;
int x;
pthread_join(thread, &ptr);
printf("%d", (int)ptr);

Foo() returning a pointer to static int (invalid and never works): All static memory in Foo() is freed when Foo() returns, before pthread_join() can copy the value.

void* Foo(void *arg)
{
   int ret = 42;
   return &ret;
}

void *ptr;
int *x;
pthread_join(thread, &ptr);
x = ptr;
printf("%d", *x);

You shouldn't do that: at your level of understanding of C casts should be simply forbidden. If you learned that in a course, this is not really high quality.

First of all, &x is the address of a pointer so the result is int** , so well two indirections.

But casting that int away is dangerous, pointers to int and void don't have necessarily the same width on different platforms. So please do

void*x;
pthread_join(tid, &x);

printf("%d",*(int*)x);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM