source: CIVL/examples/pthread/arrayloops.cvl@ 068c228

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

Updated pthread.cvh

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

  • Property mode set to 100644
File size: 2.1 KB
Line 
1/******************************************************************************
2* FILE: arrayloops.cvl
3* DESCRIPTION:
4* Example code demonstrating decomposition of array processing by
5* distributing loop iterations. A global sum is maintained by a mutex
6* variable.
7* AUTHOR: Blaise Barney
8* LAST REVISED: 01/29/09
9******************************************************************************/
10#include "pthread.cvh"
11#include <civlc.h>
12#include <stdio.h>
13#include <stdlib.h>
14
15#define NTHREADS 4
16#define ARRAYSIZE 1000000
17#define ITERATIONS ARRAYSIZE / NTHREADS
18
19double sum=0.0, a[ARRAYSIZE];
20pthread_mutex_t sum_mutex;
21
22
23void *do_work(void *tid)
24{
25 int i, start, *mytid, end;
26 double mysum=0.0;
27
28 /* Initialize my part of the global array and keep local sum */
29 mytid = (int*) tid;
30 start = (*mytid * ITERATIONS);
31 end = start + ITERATIONS;
32 printf ("Thread %d doing iterations %d to %d\n",*mytid,start,end-1);
33 for (i=start; i < end ; i++) {
34 a[i] = i * 1.0;
35 mysum = mysum + a[i];
36 }
37
38 /* Lock the mutex and update the global sum, then exit */
39 pthread_mutex_lock (&sum_mutex);
40 sum = sum + mysum;
41 pthread_mutex_unlock (&sum_mutex);
42 pthread_exit(NULL);
43}
44
45
46int main(int argc, char *argv[])
47{
48 int i, start, tids[NTHREADS];
49 pthread_t threads[NTHREADS];
50 pthread_attr_t attr;
51
52 /* Pthreads setup: initialize mutex and explicitly create threads in a
53 joinable state (for portability). Pass each thread its loop offset */
54 pthread_mutex_init(&sum_mutex, NULL);
55 pthread_attr_init(&attr);
56 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
57 for (i=0; i<NTHREADS; i++) {
58 tids[i] = i;
59 pthread_create(&threads[i], &attr, do_work, (void *) &tids[i]);
60 }
61
62 /* Wait for all threads to complete then print global sum */
63 for (i=0; i<NTHREADS; i++) {
64 pthread_join(threads[i], NULL);
65 }
66 printf ("Done. Sum= %e \n", sum);
67
68 sum=0.0;
69 for (i=0;i<ARRAYSIZE;i++){
70 a[i] = i*1.0;
71 sum = sum + a[i]; }
72 printf("Check Sum= %e\n",sum);
73
74 /* Clean up and exit */
75 pthread_attr_destroy(&attr);
76 pthread_mutex_destroy(&sum_mutex);
77 pthread_exit (NULL);
78 return 0;
79}
80
81
Note: See TracBrowser for help on using the repository browser.