添加两个使用pthread

时间:2017-07-04 03:02:52

标签: multithreading pthreads symbolicc++

请问有人帮我识别以下代码中的问题。

背景:测试代码添加了两个数组,input1& input2并使用4线程将结果存储在输出中。 问题是线程之一无法正确执行,输出缓冲区显示" 0"其中一个线程随机。任何帮助高度赞赏。

#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);
}

1 个答案:

答案 0 :(得分:1)

我找到了问题的根本原因...... &#34;&amp; i&#34;给出了未知的结果因为&#34;我&#34;内存将被++ i覆盖并且thread_id [0]在线程创建时获得不同的值...所以你应该有一个专用的内存,以免++ i发生覆盖;

&amp; i是问题...

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

要解决,请替换为&amp; shared_data [i] .... int result = pthread_create(&thread_id[i], NULL, Addition, &shared_data[i]);

shared_data是一个包含4个元素的数组..像这样

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