Pages

Monday, April 14, 2014

PThreads - Simple alignment and synchronization with a base thread

thread.c file:
#include <pthread.h> #include <semaphore.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <math.h> #define THREADS_COUNT 7 #define NITER 10000000 int count = 0; sem_t mutex; int threads_count = THREADS_COUNT; int iterations_count = NITER; pthread_t thread_first_id; short thread_first_started = 0; void *thread_function(void *data) { int i, tmp; int processed_count = 0; pid_t pid = getpid(); int *id = data; pthread_t self = pthread_self(); long thread_id = (long) self; printf("process %ld, thread %ld entering. id=%d\n", pid, thread_id, *id); if (thread_id == thread_first_id) { thread_first_started = 1; printf("Thead 1 started. Sleeping. id=%d\n", *id); usleep(2000); printf("Thead 1 started. Awaking. id=%d\n", *id); } else { while (!thread_first_started) { printf("process %ld, thread %ld waiting.\n", pid, thread_id); usleep(100); } } while (count < NITER) { sem_wait(&mutex); ++count; if (count > iterations_count) { sem_post(&mutex); break; } double x = pow(i, i); double s = sqrt(x); double c = cbrt(x); double l = log(x); double l10 = log10(x); double e = exp(x); ++processed_count; //printf("%ld - %d\n", thread_id, count); sem_post(&mutex); } printf("process %ld, thread %ld exiting. Processed items = %d, %.2f%% of total.\n", pid, thread_id, processed_count, 100.0 * processed_count / (double) iterations_count); pthread_exit(NULL); } int main(int argc, char *argv[]) { if (argc > 1) { iterations_count = atoi(argv[1]); } if (argc > 2) { threads_count = atoi(argv[2]); } printf("iterations = %d\n", iterations_count); printf("threads = %d\n", threads_count); pthread_t threads[threads_count]; int i; int *data; // Initializing unamed semaphore sem_init(&mutex, 0, 1); // Starting threads for (i = 0; i < threads_count; i++) { data = (int *) malloc(sizeof(int)); *data = i; printf("Creating thread %d with data=%d\n", i, *data); if (pthread_create(&threads[i], NULL, thread_function, (void *) data)) { printf("ERROR creating thread %d\n", i + 1); exit(1); } if (i == 0) { thread_first_id = threads[i]; } } // Waiting threads to finish for (i = 0; i < threads_count; i++) { if (pthread_join(threads[i], NULL)) { printf("\n ERROR joining thread"); exit(1); } } pthread_exit(NULL); }
Build:
gcc thread.c -lpthread -lrt -lm
Run: a.out <ITERATIONS> <THREADS COUNT>
time ./a.out 10000000 7

No comments: