source: CIVL/examples/pthread/arrayloops.cvl@ 325d439

1.23 2.0 main test-branch
Last change on this file since 325d439 was 6fe2cd9, checked in by John Edenhofner <johneden@…>, 12 years ago

Almost done

git-svn-id: svn://vsl.cis.udel.edu/civl/trunk@1040 fb995dde-84ed-4084-dfe6-e5aef3e2452c

  • Property mode set to 100644
File size: 2.4 KB
Line 
1/*****************************************************************************
2* SOURCE: This is a translation of a Pthread program from the Lawrence Livermore
3* Computing Center POSIX Threads Programming Exercise at:
4* https://computing.llnl.gov/tutorials/pthreads/exercise.html
5* FILE: arrayloops.cvl
6* DESCRIPTION:
7* Example code demonstrating decomposition of array processing by
8* distributing loop iterations. A global sum is maintained by a mutex
9* variable.
10* Command line execution:
11* civl verify -inputNTHREADS=4 -inputARRAYSIZE=1000000 arrayloops.cvl
12******************************************************************************/
13
14#include "pthread.cvh"
15#include <civlc.h>
16#include <stdio.h>
17#include <stdlib.h>
18
19$input int NTHREADS; // Changed definitions to input variables
20$input int ARRAYSIZE;
21
22#define ITERATIONS ARRAYSIZE / NTHREADS
23
24double sum=0.0, a[ARRAYSIZE];
25pthread_mutex_t sum_mutex;
26
27void *do_work(void *tid)
28{
29 int i, start, *mytid, end;
30
31 double mysum=0.0;
32 mytid = (int*) tid; // Dereference rather than direct conv
33
34 /* Initialize my part of the global array and keep local sum */
35 start = (*mytid * ITERATIONS);
36 end = start + ITERATIONS;
37 printf ("Thread %d doing iterations %d to %d\n",*mytid,start,end-1);
38
39 for (i=start; i < end ; i++) {
40 a[i] = i * 1.0;
41 mysum = mysum + a[i];
42 }
43
44 /* Lock the mutex and update the global sum, then exit */
45 pthread_mutex_lock (&sum_mutex);
46 sum = sum + mysum;
47 pthread_mutex_unlock (&sum_mutex);
48 pthread_exit(NULL, false, NULL, 0);
49}
50
51int main(void)
52{
53 int i, start, tids[NTHREADS];
54 pthread_t threads[NTHREADS];
55 pthread_attr_t attr;
56
57 /* Pthreads setup: initialize mutex and explicitly create threads in a
58 joinable state (for portability). Pass each thread its loop offset */
59 pthread_mutex_init(&sum_mutex, NULL);
60 pthread_attr_init(&attr);
61 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
62 for (i=0; i<NTHREADS; i++) {
63 tids[i] = i;
64 pthread_create(&threads[i], &attr, do_work, (void *) &tids[i]);
65 }
66
67 /* Wait for all threads to complete then print global sum */
68 for (i=0; i<NTHREADS; i++) {
69 pthread_join(threads[i], NULL);
70 }
71
72 printf ("Done. Sum= %e \n", sum);
73
74 sum=0.0;
75 for (i=0;i<ARRAYSIZE;i++){
76 a[i] = i*1.0;
77 sum = sum + a[i];
78 }
79 printf("Check Sum= %e\n",sum);
80
81 /* Clean up and exit */
82 pthread_attr_destroy(&attr);
83 pthread_mutex_destroy(&sum_mutex);
84 pthread_exit (NULL, true, NULL, 0);
85 return 0;
86}
87
88
Note: See TracBrowser for help on using the repository browser.