#include #include #include #define NUM_THREADS 10 #define MSG_LEN 100 struct thread_data { char *msg; }; typedef struct thread_data thread_data_t; void *PrintHello(void *arg) { thread_data_t *td = (thread_data_t *) arg; printf("%s", td->msg); pthread_exit(NULL); } void dienomem() { printf("ERROR: No memory?!\n"); exit(1); } int main(void) { pthread_t threads[NUM_THREADS]; for (int t = 0; t < NUM_THREADS; t++) { /* printf("Creating thread %d\n", t); */ thread_data_t *td = malloc(sizeof(thread_data_t)); if (!td) dienomem(); td->msg = malloc(MSG_LEN); if (!td->msg) dienomem(); snprintf(td->msg, MSG_LEN, "Hello, I'm thread %d!\n", t); int rc = pthread_create(&threads[t], NULL, PrintHello, (void *) td); if (rc) { printf("ERROR: return code from pthread_create() is %d\n", rc); exit(1); } } pthread_exit(NULL); /* Wait for the threads to finish. */ }