// CS 450; Thread example 2: Pass argument to 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; // argument to pass to thread // 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); printf("Thread argument at %p\n", &thd_arg); // Wait for thread to finish // pthread_join(thd, NULL); } // Thread task takes pointer to an argument value. // void *task(void *arg) { int *my_arg_ptr = (int *) arg; int my_arg = *my_arg_ptr; printf("Thread called with argument %d at %p\n", my_arg, arg); return NULL; } /* Output: Thread creation returned code = 0 Thread called with argument 17 at 0x7fff5c89dac8 Thread argument at 0x7fff5c89dac8 */ // Note: Last two lines could be swapped