thread_hello.c
/* File:
* thread_hello.c
*
* Purpose:
* Illustrate basic use of pthreads: create some threads,
* each of which prints a message.
*
* Input:
* none
* Output:
* message from each thread
*
* Compile: gcc -g -Wall -o thread_hello thread_hello.c -pthread
* Usage:
* ./thread_hello <thread_count>
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
/* Global variable: accessible to all threads */
int num_threads;
void *hello(void * thread_number);
int main(int argc, char* argv[]) {
if (argc != 2) {
printf("usage: %s <number of threads>\n", argv[0]);
return EXIT_SUCCESS;
}
num_threads = atoi(argv[1]);
if (num_threads <= 0) {
return EXIT_FAILURE;
}
pthread_t* thread_handles;
thread_handles = malloc(num_threads * sizeof(pthread_t));
int thread;
for (thread = 0; thread < num_threads; thread++) {
pthread_create(
&thread_handles[thread],
NULL,
hello,
(void *) (long) thread);
}
printf("Hello from the main thread\n");
for (thread = 0; thread < num_threads; thread++) {
pthread_join(thread_handles[thread], NULL);
}
free(thread_handles);
return 0;
}
void *hello(void* thread_number) {
printf("Hello from thread %ld of %d\n", (long) thread_number, num_threads);
return NULL;
}