You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1006 B
C

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#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(int argc, char *argv[]) {
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. */
}