/* * Simple Thread Example * It just creates two threads. Prints messages then exit. * * APIs used are: * 1. pthread_create * 2. pthread_attr_init * 3. pthread_join */ #include #include #include #include #define RETVAL_CHECK(retval,func_name) if(retval) {printf("Function '%s' returned error value %d\n", func_name, retval);} /* * Start routine for the thread. * This is thread's starting point. Like main() for process. */ void *thread_start_routine( void *ptr ) { char *threadName = (char*)ptr; printf("%-15s: Called\n", threadName); sleep(10); printf("%-15s: Completed\n", threadName); return 0; } /* * Main Function */ int main() { pthread_t thread1, thread2; pthread_attr_t tattr; int retval; /* Create Thread with default behavior - null attributes object used */ retval = pthread_create(&thread1, NULL, thread_start_routine, (void*) "First Thread"); RETVAL_CHECK(retval,"pthread_create"); /* Initialized by default thread attributes */ retval = pthread_attr_init(&tattr); RETVAL_CHECK(retval,"pthread_attr_init"); /* Create Thread with default behavior - attributes object with default setup */ retval = pthread_create(&thread2, &tattr, thread_start_routine, (void*) "Second Thread"); RETVAL_CHECK(retval,"pthread_create"); pthread_join( thread1, NULL); sleep(2); pthread_join( thread2, NULL); return 0; }