#include #include #include #include #include /* int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void* (*start_routine)(void*), void *arg); */ // thread shared data typedef struct { size_t thread_count; size_t position; pthread_mutex_t mutex; } shared_data_t; // thread private data typedef struct { size_t thread_id; shared_data_t* shared_data; } private_data_t; void* run(void* data) { private_data_t* private_data = (private_data_t*)data; shared_data_t* shared_data = private_data->shared_data; pthread_mutex_lock( &shared_data->mutex ); ++shared_data->position; printf("thread %zu/%zu I arrived at position %zu\n" , private_data->thread_id, shared_data->thread_count , shared_data->position); pthread_mutex_unlock( &shared_data->mutex ); return NULL; } int main(int argc, char* argv[]) { size_t thread_count = sysconf(_SC_NPROCESSORS_ONLN); if ( argc >= 2 ) { if ( sscanf(argv[1], "%zu", &thread_count) != 1 || thread_count == 0 ) return (void)fprintf(stderr, "hello_w: error: invalid thread count: %s\n", argv[1]), 1; } pthread_t* threads = (pthread_t*)malloc(thread_count * sizeof(pthread_t)); if ( threads == NULL ) return (void)fprintf(stderr, "hello_w: error: could not allocate memory for: %zu threads\n", thread_count), 2; struct timespec start_time; clock_gettime(CLOCK_MONOTONIC, &start_time); shared_data_t shared_data; shared_data.thread_count = thread_count; shared_data.position = 0; pthread_mutex_init(&shared_data.mutex, NULL); private_data_t* private_data = (private_data_t*) calloc(thread_count, sizeof(private_data_t)); for ( size_t index = 0; index < thread_count; ++index ) { private_data[index].thread_id = index; private_data[index].shared_data = &shared_data; pthread_create(&threads[index], NULL, run, private_data + index); } pthread_mutex_lock( &shared_data.mutex ); printf("Hello from main thread\n"); pthread_mutex_unlock( &shared_data.mutex ); for ( size_t index = 0; index < thread_count; ++index ) pthread_join(threads[index], NULL); struct timespec finish_time; clock_gettime(CLOCK_MONOTONIC, &finish_time); double seconds = finish_time.tv_sec - start_time.tv_sec + (finish_time.tv_nsec - start_time.tv_nsec) * 1e-9; printf("Thread creation and join time: %.9lfs\n", seconds); pthread_mutex_destroy(&shared_data.mutex); free(private_data); free(threads); return 0; }