The program uses two threads to populate items in a shared array. Each thread tries to add 25,000 values to the array from 1 to 1,000. The problem is, if the data structure is not thread safe, when two threads attemp to access it simulaneously they race, resulting in data loss. Add synchronization primitives to make this array based data structure thread safe.
#include #include #include #include #include // Global Address Space #define ARRAY_SIZE 50000 #define DEBUG 0 typedef struct __syncarray { long value[ARRAY_SIZE]; int index; } syncarray; void init(syncarray *c) { int i; for (i=0; ivalue[i] = 0; c->index = 0; } int put(syncarray *c, long val) { int store_index = c->index; if (store_index < ARRAY_SIZE) { #if DEBUG printf("Store %ld at %d. [%d] ",val,store_index,c->index); #endif c->value[store_index] = val; c->index = c->index + 1; } else store_index = -1; return store_index; } long get(syncarray *c, int index) { long rc = c->value[index]; return rc; } long sum(syncarray *c) { int i; long sum = 0; for (i=0;ivalue[i]; return sum; } long avg(syncarray *c) { return sum(c) / ARRAY_SIZE; } void *worker(void *arg) { long counter = 0; struct timespec ts; syncarray *sa = (syncarray *) arg; int rc = 0; while ((rc != -1) && (counter < 25000)) { clock_gettime(CLOCK_REALTIME, &ts); #if DEBUG printf("Storing %ld ", counter); #endif //rc = put(sa,ts.tv_nsec); counter ++; rc = put(sa,counter); } return NULL; } int main (int argc, char * argv[]) { pthread_t p1; pthread_t p2; syncarray sa; init(&sa); printf("The initial sum is %ld ",sum(&sa)); // Launch threads pthread_create(&p1, NULL, worker, &sa); pthread_create(&p2, NULL, worker, &sa); pthread_join(p1, NULL); pthread_join(p2, NULL); printf("The sum is %ld ",sum(&sa)); printf("The avg is %ld ",avg(&sa)); // Print output return 0; }