/***************************************************************************** * SOURCE: This is a translation of a Pthread program from the Lawrence Livermore * Computing Center POSIX Threads Programming Exercise at: * https://computing.llnl.gov/tutorials/pthreads/exercise.html * FILE: arrayloops.cvl * DESCRIPTION: * Example code demonstrating decomposition of array processing by * distributing loop iterations. A global sum is maintained by a mutex * variable. * Command line execution: * civl verify -inputNTHREADS=4 -inputARRAYSIZE=1000000 arrayloops.cvl ******************************************************************************/ #include "pthread.cvh" #include #include #include $input int NTHREADS; // Changed definitions to input variables $input int ARRAYSIZE; #define ITERATIONS ARRAYSIZE / NTHREADS double sum=0.0, a[ARRAYSIZE]; pthread_mutex_t sum_mutex; void *do_work(void *tid) { int i, start, *mytid, end; double mysum=0.0; mytid = (int*) tid; // Dereference rather than direct conv /* Initialize my part of the global array and keep local sum */ start = (*mytid * ITERATIONS); end = start + ITERATIONS; printf ("Thread %d doing iterations %d to %d\n",*mytid,start,end-1); for (i=start; i < end ; i++) { a[i] = i * 1.0; mysum = mysum + a[i]; } /* Lock the mutex and update the global sum, then exit */ pthread_mutex_lock (&sum_mutex); sum = sum + mysum; pthread_mutex_unlock (&sum_mutex); pthread_exit(NULL, false, NULL, 0); } int main(void) { int i, start, tids[NTHREADS]; pthread_t threads[NTHREADS]; pthread_attr_t attr; /* Pthreads setup: initialize mutex and explicitly create threads in a joinable state (for portability). Pass each thread its loop offset */ pthread_mutex_init(&sum_mutex, NULL); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i=0; i