简体   繁体   中英

pthread_self returning different values

I am learning threads using C and found the following 'Hello World' program. When I am printing the vale of pthread_value() within the thread and outside the thread using pthread_join() the values returned by the two threads are completely different.

/******************************************************************************
* FILE: hello.c
* DESCRIPTION:
*   A "hello world" Pthreads program.  Demonstrates thread creation and
*   termination.
* AUTHOR: Blaise Barney
* LAST REVISED: 08/09/11
******************************************************************************/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
   long tid;
   tid = (long)threadid;
   printf("Hello World! It's me, thread #%ld!, %ld\n", tid, pthread_self());
   long a=  pthread_self();
   //pthread_exit(NULL);
        long *p = &a;
   return p;
}

int main(int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   void *status;
   long t;
   FILE* file = fopen("test.txt", "r");
   for(t=0;t<NUM_THREADS;t++){
     printf("In main: creating thread %ld\n", t);
     rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
     if (rc){
       printf("ERROR; return code from pthread_create() is %d\n", rc);
       exit(-1);
       }
     }
   for(t=0; t<NUM_THREADS;t++){
     pthread_join(threads[t], &status);
     printf("%ld\n",(long)status);

        }
   /* Last thing that main() should do */
   pthread_exit(NULL);
}

Your PrintHello() function returns the address of a local variable. Trying to use that address after the function exits is undefined and anything can happen, from getting a garbage value to your program crashing. Plus instead of dereferencing that address to get at the value it points to (Assuming it was still valid, which, again, it's not), you cast the address to a long and print out the address itself. I doubt that's what you intended to do. The general approach should be to malloc enough memory in the thread to hold its return value, and returning that address. Then in the joining thread, dereference that returned address to get at the actual returned value, and free that memory when done.

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