#include #include #include #include #include #include /* #define DEBUG */ /* #define PROFILING */ #define ITERATIONS 1024 #define NUM_THREADS 1024 #define MAX_SLEEP 1000000 useconds_t musec[ITERATIONS]; unsigned long seed = 62; pthread_t tid[NUM_THREADS]; int id[NUM_THREADS]; void timevalsub(struct timeval *t1, const struct timeval *t2) { t1->tv_sec -= t2->tv_sec; t1->tv_usec -= t2->tv_usec; if (t1->tv_usec < 0) { t1->tv_sec--; t1->tv_usec += 1000000; } if (t1->tv_usec >= 1000000) { t1->tv_sec++; t1->tv_usec -= 1000000; } } static void init(void) { int i; srandom(seed); for (i = 0; i < ITERATIONS; ++i) { musec[i] = random() % MAX_SLEEP; #ifdef DEBUG printf("Iteration: %d num: %d \n", i, musec[i]); #endif } return; } static void do_usleep(int *tid) { int i, step; i = 0; for(;;) { step = (i + *tid) % ITERATIONS; #ifdef DEBUG printf("Id: %d iter: %d num: %d \n", pthread_self(), i, musec[step]); #endif usleep(musec[step]); if (i < ITERATIONS) i++; else break; } return; } int main(void) { int i, r_val; #ifdef PROFILING struct timeval btp, atp; #endif init(); #ifdef PROFILING gettimeofday(&btp, NULL); #endif for (i = 0; i < NUM_THREADS; ++i) { id[i] = i; r_val = pthread_create(&tid[i], NULL, (void *) &do_usleep, &id[i]); if (r_val == -1) perror("Error in pthread_create()\n"); } for (i = 0; i < NUM_THREADS; ++i) { r_val = pthread_join(tid[i], NULL); if (r_val == -1) perror("Error in pthread_join()\n"); } #ifdef PROFILING gettimeofday(&atp, NULL); timevalsub(&atp, &btp); printf("Time elapsed: %ld.%ld \n", atp.tv_sec, atp.tv_usec); #endif return (0); }