source: CIVL/examples/pthread/bug6.c@ f6ce0eb

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

Updated pthread.cvh and examples

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

  • Property mode set to 100644
File size: 2.2 KB
RevLine 
[cf74da3]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 */
16#define NUMTHRDS 8
17#define VECLEN 100000
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
43
44
45int main (int argc, char *argv[])
46{
47long i;
48void *status;
49pthread_t threads[NUMTHRDS];
50pthread_attr_t attr;
51
52/* Assign storage and initialize values */
53a = (int*) malloc (NUMTHRDS*VECLEN*sizeof(int));
54b = (int*) malloc (NUMTHRDS*VECLEN*sizeof(int));
55
56for (i=0; i<VECLEN*NUMTHRDS; i++)
57 a[i]= b[i]=1;
58
59/* Create threads as joinable, each of which will execute the dot product
60 * routine. Their offset into the global vectors is specified by passing
61 * the "i" argument in pthread_create().
62 */
63pthread_attr_init(&attr);
64pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
65for(i=0; i<NUMTHRDS; i++)
66 pthread_create(&threads[i], &attr, dotprod, (void *)i);
67
68pthread_attr_destroy(&attr);
69
70/* Wait on the threads for final result */
71for(i=0; i<NUMTHRDS; i++)
72 pthread_join(threads[i], &status);
73
74/* After joining, print out the results and cleanup */
75printf ("Final Global Sum=%li\n",sum);
76free (a);
77free (b);
78pthread_exit(NULL);
79}
80
81
Note: See TracBrowser for help on using the repository browser.