#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct
{
size_t thread_num;
size_t thread_count;
} private_data_t;
void* run(void* data)
{
private_data_t* private_data = (private_data_t*)data;
size_t thread_num = (*private_data).thread_num;
size_t thread_count = private_data->thread_count;
printf("Hello world from secondary thread %zu of %zu\n", thread_num, thread_count);
return NULL;
}
int main(int argc, char* argv[])
{
size_t thread_count = sysconf(_SC_NPROCESSORS_ONLN);
if ( argc >= 2 )
thread_count = strtoull(argv[1], NULL, 10);
pthread_t* threads = (pthread_t*) malloc(thread_count * sizeof(pthread_t));
if ( threads == NULL )
return (void)fprintf(stderr, "error: could not allocate memory for %zu threads\n", thread_count), 1;
private_data_t* private_data = (private_data_t*) calloc(thread_count, sizeof(private_data_t));
if ( private_data == NULL )
return (void)fprintf(stderr, "error: could not allocate private memory for %zu threads\n", thread_count), 3;
for ( size_t index = 0; index < thread_count; ++index )
{
private_data[index].thread_num = index;
private_data[index].thread_count = thread_count;
pthread_create(&threads[index], NULL, run, &private_data[index]);
}
printf("Hello world from main thread\n");
for ( size_t index = 0; index < thread_count; ++index )
pthread_join(threads[index], NULL);
free(private_data);
free(threads);
return 0;
}