#include #include #include #include #include #include pthread_mutex_t mutex; typedef struct __task { long n; float x; struct __task * next; } TASK; TASK * tasks = NULL; typedef unsigned long long ticks; static __inline__ ticks getticks(void) { unsigned a, d; asm volatile("rdtsc" : "=a" (a), "=d" (d)); return ((ticks)a) | (((ticks)d) << 32); } void * worker(void * x) { int wno = *((int *) x); int * taskno = (int *) calloc(1, sizeof(int)); *taskno = 0; #ifdef DEBUG printf("Worker no %d created\n", wno); #endif while(1==1) { // get a task from the list pthread_mutex_lock(&mutex); TASK * t = tasks; if(tasks!=NULL) { tasks = tasks->next; } pthread_mutex_unlock(&mutex); // process if(t == NULL) break; // nothing else to process #ifdef DEBUG printf("Thread %ld processing task <%ld,%f>\n",pthread_self(), t->n, t->x); #endif { long l; for(l=0; ln; l++) t->x = sin(t->x); } // write results #ifdef DEBUG printf("Thread %ld computed %f\n",pthread_self(),t->x); #endif (*taskno)++; } return ((void *) taskno); } int main(int argc, char * argv[]) { int opt, nw, m, i ; float ta,tb,elapsed; pthread_t *w; struct timeval t0, t1; clock_t before, after; struct timespec c0,c1,p0,p1; ticks tck0, tck1; while((opt = getopt(argc, argv, "n:m:"))!= (-1)) { switch(opt) { case 'n': { nw = atoi(optarg); break; } case 'm': { m = atoi(optarg); break; } default: { printf("Usage is:\n%s -n pardegree -m streamlenght\n", argv[0]); return(0); } } } #ifdef DEBUG printf("%d workers and %d tasks\n", nw, m); #endif w = (pthread_t *) calloc(nw, sizeof(pthread_t)); if((pthread_mutex_init(&mutex,NULL)!=0)) { printf("Failed to initialize the mutex\n"); return(-1); } for(i=0; ix = (float)i ; t->n = (long) i*(100000L); pthread_mutex_lock(&mutex); // may be in principle concurrent with task consuming t->next = tasks; tasks = t; pthread_mutex_unlock(&mutex); } before = clock(); clock_gettime(CLOCK_THREAD_CPUTIME_ID,&c0); clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&p0); gettimeofday(&t0,NULL); tck0 = getticks(); #ifdef DEBUG printf("Start %ld %ld \n", t0.tv_sec, t0.tv_usec); #endif for(i=0; i