// CS 450; Thread example 3: Get result from thread // version 2014-01-25 3:43 PM // #include #include void *task(void *arg); // prototype int main(void) { pthread_t thd; // thread int retcode; // 0 if thread creation succeeded int thd_arg = 17; // Create thread and have it run task; pass // (pointer to) thread argument // retcode = pthread_create(&thd, NULL, task, (void *) &thd_arg); printf("Thread creation returned code = %d\n", retcode); int *resultptr; pthread_join(thd, (void **) &resultptr); printf("result at %p\n", resultptr); if (resultptr != NULL) { printf("result = %d\n", *resultptr); } } int nonlocal; // task will return ptr to this variable // task can't return ptr to local variable // Task returns pointer to its result // void *task(void *arg) { int my_arg = *(int *) arg; printf("Thread called with argument %d\n", my_arg); nonlocal = my_arg * 2; printf("nonlocal at %p\n", &nonlocal); return &nonlocal; } /* Output Thread creation returned code = 0 Thread called with argument 17 nonlocal at 0x100001078 result at 0x100001078 */