source: CIVL/examples/pthread/arrayloops.cvl@ 37bfb99

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

Updated examples and pthread.cvh

git-svn-id: svn://vsl.cis.udel.edu/civl/trunk@1039 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#include "pthread.cvh"
14#include <civlc.h>
15#include <stdio.h>
16#include <stdlib.h>
17
18$input int NTHREADS; // Changed definitions to input variables
19$input int ARRAYSIZE;
20
21#define ITERATIONS ARRAYSIZE / NTHREADS
22
23double sum=0.0, a[ARRAYSIZE];
24pthread_mutex_t sum_mutex;
25
26
27void *do_work(void *tid)
28{
29 int i, start, *mytid, end;
30 double mysum=0.0;
31
32 /* Initialize my part of the global array and keep local sum */
33 mytid = (int*) tid;
34 start = (*mytid * ITERATIONS);
35 end = start + ITERATIONS;
36 printf ("Thread %d doing iterations %d to %d\n",*mytid,start,end-1);
37 for (i=start; i < end ; i++) {
38 a[i] = i * 1.0;
39 mysum = mysum + a[i];
40 }
41 /* Lock the mutex and update the global sum, then exit */
42 pthread_mutex_lock (&sum_mutex);
43 sum = sum + mysum;
44 pthread_mutex_unlock (&sum_mutex);
45 pthread_exit(NULL, false, NULL, 0);
46}
47
48
49int main(void)
50{
51 int i, start, tids[NTHREADS];
52 pthread_t threads[NTHREADS];
53 pthread_attr_t attr;
54
55 /* Pthreads setup: initialize mutex and explicitly create threads in a
56 joinable state (for portability). Pass each thread its loop offset */
57 pthread_mutex_init(&sum_mutex, NULL);
58 pthread_attr_init(&attr);
59 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
60 for (i=0; i<NTHREADS; i++) {
61 tids[i] = i;
62 pthread_create(&threads[i], &attr, do_work, (void *) &tids[i]);
63 }
64
65 /* Wait for all threads to complete then print global sum */
66 for (i=0; i<NTHREADS; i++) {
67 pthread_join(threads[i], NULL);
68 }
69 printf ("Done. Sum= %e \n", sum);
70
71 sum=0.0;
72 for (i=0;i<ARRAYSIZE;i++){
73 a[i] = i*1.0;
74 sum = sum + a[i]; }
75 printf("Check Sum= %e\n",sum);
76
77 /* Clean up and exit */
78 pthread_attr_destroy(&attr);
79 pthread_mutex_destroy(&sum_mutex);
80 pthread_exit (NULL, true, NULL, 0);
81 return 0;
82}
83
84
Note: See TracBrowser for help on using the repository browser.