//Compile with // dcc -pthread etc.... #include #include #include #include #include #include #include #define NUM_THREADS 3 void *do_stuff(void *argument) { int *arg; arg = argument; int *val = malloc(sizeof(int)); *val = *arg *2; printf("Thread processing with arg %d returning %d\n",*arg, *val); return val; } int main(int argc, char** argv) { int args[NUM_THREADS]; int res; pthread_t threads[NUM_THREADS]; // create all threads one by one for (int i = 0; i < NUM_THREADS; ++i) { args[i] = i; printf("In main: creating thread %d\n", i); res = pthread_create(&threads[i], NULL, do_stuff, &args[i]); } // wait for each thread to complete // otherwise the main thread will die and all threads will die for (int i = 0; i < NUM_THREADS; ++i) { void *retval; // block until thread 'i' completes res = pthread_join(threads[i], &retval); if(res < 0){ fprintf(stderr, "Error: Joining threads\n"); return 1; } int *result; result = retval; printf("In main: thread %d has completed\n", i); printf("retval %d\n",*result); free(retval); } printf("In main: All threads completed successfully\n"); return 0; }