source: CIVL/examples/translation/pthread/bug6.c@ aef8b11

1.23 2.0 acw/focus-triggers main test-branch
Last change on this file since aef8b11 was aef8b11, checked in by Manchun Zheng <zmanchun@…>, 12 years ago

minor correction

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

  • Property mode set to 100644
File size: 2.2 KB
RevLine 
[506de9d]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.h>
12#include <stdio.h>
13#include <stdlib.h>
14
15/* Define global data where everyone can see them */
[aef8b11]16#define NUMTHRDS 3
17#define VECLEN 4
[506de9d]18int *a, *b;
19long sum=0;
20
21void *dotprod(void *arg)
22{
23 /* Each thread works on a different set of data.
24 * The offset is specified by the arg parameter. The size of
25 * the data for each thread is indicated by VECLEN.
26 */
27 int i, start, end, offset, len;
28 long tid = (long)arg;
29 offset = tid;
30 len = VECLEN;
31 start = offset*len;
32 end = start + len;
33
34/* Perform my section of the dot product */
35 printf("thread: %ld starting. start=%d end=%d\n",tid,start,end-1);
36 for (i=start; i<end ; i++)
37 sum += (a[i] * b[i]);
38 printf("thread: %ld done. Global sum now is=%li\n",tid,sum);
39
40 pthread_exit((void*) 0);
41}
42
43int main (int argc, char *argv[])
44{
45long i;
46void *status;
47pthread_t threads[NUMTHRDS];
48pthread_attr_t attr;
49
50/* Assign storage and initialize values */
51a = (int*) malloc (NUMTHRDS*VECLEN*sizeof(int));
52b = (int*) malloc (NUMTHRDS*VECLEN*sizeof(int));
53
54for (i=0; i<VECLEN*NUMTHRDS; i++)
55 a[i]= b[i]=1;
56
57/* Create threads as joinable, each of which will execute the dot product
58 * routine. Their offset into the global vectors is specified by passing
59 * the "i" argument in pthread_create().
60 */
61pthread_attr_init(&attr);
62pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
63for(i=0; i<NUMTHRDS; i++)
64 pthread_create(&threads[i], &attr, dotprod, (void *)i);
65
66pthread_attr_destroy(&attr);
67
68/* Wait on the threads for final result */
69for(i=0; i<NUMTHRDS; i++)
70 pthread_join(threads[i], &status);
71
72/* After joining, print out the results and cleanup */
73printf ("Final Global Sum=%li\n",sum);
74free (a);
75free (b);
76pthread_exit(NULL);
77}
78
79
Note: See TracBrowser for help on using the repository browser.