Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why my program throws 14000000 instead of 10000000 using threads?

i wrote a simple c program to make every thread multiplate its index by 1000000 and add it to sum , i created 5 threads so the logic answer would be (0+1+2+3+4)*1000000 which is 10000000 but it throws 14000000 instead .could anyone helps me understanding this?

#include<pthread.h>
#include<stdio.h>

typedef struct argument {
    int index;
    int sum;
} arg;

void *fonction(void *arg0) {
    ((arg *) arg0) -> sum += ((arg *) arg0) -> index * 1000000;
}
int main() {
    pthread_t thread[5];
    int order[5];
    arg a;
    for (int i = 0; i < 5; i++)
        order[i] = i;
    a.sum = 0;
    for (int i = 0; i < 5; i++) {
        a.index = order[i];
        pthread_create(&thread[i], NULL, fonction, &a);
    }
    for (int i = 0; i < 5; i++)
        pthread_join(thread[i], NULL);

    printf("%d\n", a.sum);

    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It is 140.. because the behavior is undefined. The results will differ on different machine. The issue comes down to two things both because all threads are accessing the same object (see &a given when creating thread).

  • When each thread runs it accesses the same index (as part of accessing a member of the same object (&a)); thus the assumption that the threads will see 0..4 is incorrect from the start: multiple threads might see the same value of index, such as 2,2,2,4,4..

  • When each thread updates sum it has to read and write to the same shared memory. For example, it could be lack of memory visibility (thread X doesn’t see value updated from thread Y) or it could be a conflicting thread schedule between the read and write (thread X read, thread Y read, thread X write, thread Y write) etc..

If creating a new arg object for each thread, then both of these problems is fixed. While the sum issue can be fixed with the appropriate locking, the index issue can only be fixed by not sharing the object given as the thread input.

// create 5 arg objects, one for each thread
arg a[5];

for (..) {
    a[i].index = i;
    // give DIFFERENT object to each thread
    pthread_create(.., &a[i]);
}

// after all threads complete
int sum = 0;
for (..) {
    sum += a[i].result;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading