/** * compile with: $] gcc thread_example.c -lpthread -o thread_example * run with: $] ./thread_example * */ #include #include #include #include // the function which a thread is supposed to run // has the following prototype void *thread1_function( void *ptr ); void *thread2_function( void *ptr ); int length = -1; pthread_t thread1, thread2; main() { char *message1 = "Thread 1"; int iret1, iret2; /* Create independent threads each of which will execute function */ iret1 = pthread_create( &thread1, NULL, thread1_function, (void*) message1); iret2 = pthread_create( &thread2, NULL, thread2_function, NULL); /* Wait till threads are complete before main continues. Unless we */ /* wait we run the risk of executing an exit which will terminate */ /* the process and all threads before the threads have completed. */ pthread_join( thread2, NULL); // return value of 0 signifies success // typically the return value should be checked for error conditions printf("Thread 1 returns: %d\n",iret1); printf("Thread 2 returns: %d\n",iret2); exit(0); } /* The function executed by thread 1. * For example, this thread could continuously listen on a socket for * incoming data, and update a (global) data structure. */ void *thread1_function( void *ptr ) { // this thread prints a message (passed as argument) and assigns // the length to a global variable char *message; message = (char *) ptr; printf("Thread 1 message:%s \n", message); length = strlen(message); } /* The function executed by thread 2. * For example, this thread could listen for user input * and then read from the data structure. */ void *thread2_function( void *ptr ) { // note that the argument is not used // we wait till thread1 has completed pthread_join( thread1, NULL); printf("Thread 2: length = %d\n", length); }