source: CIVL/examples/pthread/bug6.cvl@ 4b4bbb3

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

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

  • Property mode set to 100644
File size: 2.3 KB
Line 
1/*****************************************************************************
2* FILE: bug6.c
3* DESCRIPTION:
4* This example demonstrates a race condition with a global variable that
5* gives obviously wrong results. Figure out how to fix the problem - or see
6* bug6fix.c for one solution. The dotprod_mutex.c example provides a much
7* more efficient way of solving this problem than bug6fix.c (FYI).
8* SOURCE: 07/06/05 Blaise Barney
9* LAST REVISED: 01/29/09 Blaise Barney
10******************************************************************************/
11#include "pthread.cvh"
12#include <civlc.h>
13#include <stdio.h>
14#include <stdlib.h>
15
16/* Define global data where everyone can see them */
17#define NUMTHRDS 8
18#define VECLEN 100000
19int *a, *b;
20long sum=0;
21
22void *dotprod(void *arg)
23{
24 /* Each thread works on a different set of data.
25 * The offset is specified by the arg parameter. The size of
26 * the data for each thread is indicated by VECLEN.
27 */
28 int i, start, end, offset, len;
29 long tid = (long)arg;
30 offset = tid;
31 len = VECLEN;
32 start = offset*len;
33 end = start + len;
34
35/* Perform my section of the dot product */
36 printf("thread: %ld starting. start=%d end=%d\n",tid,start,end-1);
37 for (i=start; i<end ; i++)
38 sum += (a[i] * b[i]);
39 printf("thread: %ld done. Global sum now is=%li\n",tid,sum);
40
41 pthread_exit((void*) 0);
42}
43
44
45
46int main (int argc, char *argv[])
47{
48 long i;
49 void *status;
50 pthread_t threads[NUMTHRDS];
51 pthread_attr_t attr;
52
53 /* Assign storage and initialize values */
54 a = (int*) malloc (NUMTHRDS*VECLEN*sizeof(int));
55 b = (int*) malloc (NUMTHRDS*VECLEN*sizeof(int));
56
57 for (i=0; i<VECLEN*NUMTHRDS; i++)
58 a[i]= b[i]=1;
59
60 /* Create threads as joinable, each of which will execute the dot product
61 * routine. Their offset into the global vectors is specified by passing
62 * the "i" argument in pthread_create().
63 */
64 pthread_attr_init(&attr);
65 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
66 for(i=0; i<NUMTHRDS; i++)
67 pthread_create(&threads[i], &attr, dotprod, (void *)i);
68
69 pthread_attr_destroy(&attr);
70
71 /* Wait on the threads for final result */
72 for(i=0; i<NUMTHRDS; i++)
73 pthread_join(threads[i], &status);
74
75 /* After joining, print out the results and cleanup */
76 printf ("Final Global Sum=%li\n",sum);
77 free (a);
78 free (b);
79 pthread_exit(NULL);
80}
81
82
Note: See TracBrowser for help on using the repository browser.