scharupa
scharupa

Reputation: 21

Addition of two arrays not working using pthread

Could you please some one help me to identify the issues in the following code.

Background: The test code adds two arrays, input1 & input2 and stores the results in output, using 4-threads. The problem was one of the thread not able to do correctly, output buffer shows "0" randomly for one of the threads. Any help highly appreciated.

#include<iostream>
#include<pthread.h>
#include<unistd.h>
using namespace std;
int input1[1000], input2[1000], output[1000]; 

void* Addition(void* offset) {
    int *local_offset = (int*)offset;
    for(int i = ((*local_offset) * 250); i < ((*local_offset)+1)*250; ++i) {
            output[i] = input1[i] + input2[i];
    }
    pthread_exit(0);
}

int main() {
    pthread_t thread_id[4];
    void* status;
    fill_n(input1, 1000, 3); // input1, fill the buffer with 3
    fill_n(input2, 1000, 4); // input2, fill the buffer with 4
    fill_n(output, 1000, 0); // output, fill the buffer with 0

    // create 4 thread with load of 250items
    for(int i = 0; i < 4; ++i) {
            int result = pthread_create(&thread_id[i], NULL, Addition, &i);
            if(result) cout << "Thread creation failed" << endl;
    }

    // join the 4-threads
    for(int i = 0; i < 4; ++i) {
            int result = pthread_join(thread_id[i], &status);
            if(result) cout << "Join failed " << i << endl;
    }

    // print output buffer, the output buffer not updated properly, 
    // noticed"0" for 1 & 2 thread randomly 
    for(int i =0; i < 1000; ++i)
            cout << i << " " << output[i] << endl;

    pthread_exit(NULL);
}

Upvotes: 1

Views: 333

Answers (1)

scharupa
scharupa

Reputation: 21

I have found the root cause of the issue... The "&i" gives unknown result because "i" memory will be overwritten by ++i and thread_id[0] get different value by the time the thread created... so you should have a dedicated memory so that no overwriting will happen by ++i;

&i is the problem...

int result = pthread_create(&thread_id[i], NULL, Addition, &i);

To solve, replace with &shared_data[i] .... int result = pthread_create(&thread_id[i], NULL, Addition, &shared_data[i]);

The shared_data is an array of 4 elements.. like this

int shared_data[4] = {0,1,2,3};

Upvotes: 1

Related Questions