// Sample code that demonstrates the use of pthread_create and pthread_join. // Multiple threads print out a sequence of numbers using printf. // Although created in order, execution order will vary. // For small LOOP_NUM, likely won't get interleaving of threads. // // Remember to compile with -pthread #include #include #include #define NUM_THREADS 4 #define LOOP_NUM 10 // print out a sequence of LOOP_NUM numbers with thread identifying number void *thread_main(void *arg) { int *num = (int *) arg; // read void * argument as intended for (int i = 0; i < LOOP_NUM; i++) { printf("[thread %d] %d\n", *num, i); } free(num); // child thread cleans up the memory allocated for its argument return NULL; // return type is a pointer } int main(int argc, char** argv) { pthread_t thds[NUM_THREADS]; // array of thread ids // create threads to run thread_main() for (int i = 0; i < NUM_THREADS; i++) { int *num = (int*)malloc(sizeof(int)); *num = i; if (pthread_create(&thds[i], NULL, &thread_main, num) != 0) { fprintf(stderr, "pthread_create failed\n"); } } // No need to join every child since we don't need to do anything after // joining them. instead, just call pthread_exit(). // Note that we can't use return otherwise the entire process will be // cleaned up and thus other threads may not finish. pthread_exit(NULL); }