source: CIVL/examples/pthread/arrayloops.cvl@ f78d8ad

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

Updated examples and Makefile

git-svn-id: svn://vsl.cis.udel.edu/civl/trunk@1029 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 printf("1");
42 /* Lock the mutex and update the global sum, then exit */
43 pthread_mutex_lock (&sum_mutex);
44 sum = sum + mysum;
45 pthread_mutex_unlock (&sum_mutex);
46 pthread_exit(NULL);
47}
48
49
50int main(void)
51{
52 int i, start, tids[NTHREADS];
53 pthread_t threads[NTHREADS];
54 pthread_attr_t attr;
55
56 /* Pthreads setup: initialize mutex and explicitly create threads in a
57 joinable state (for portability). Pass each thread its loop offset */
58 pthread_mutex_init(&sum_mutex, NULL);
59 pthread_attr_init(&attr);
60 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
61 for (i=0; i<NTHREADS; i++) {
62 tids[i] = i;
63 pthread_create(&threads[i], &attr, do_work, (void *) &tids[i]);
64 }
65
66 /* Wait for all threads to complete then print global sum */
67 for (i=0; i<NTHREADS; i++) {
68 pthread_join(threads[i], NULL);
69 }
70 printf ("Done. Sum= %e \n", sum);
71
72 sum=0.0;
73 for (i=0;i<ARRAYSIZE;i++){
74 a[i] = i*1.0;
75 sum = sum + a[i]; }
76 printf("Check Sum= %e\n",sum);
77
78 /* Clean up and exit */
79 pthread_attr_destroy(&attr);
80 pthread_mutex_destroy(&sum_mutex);
81 pthread_exit (NULL);
82 return 0;
83}
84
85
Note: See TracBrowser for help on using the repository browser.