请有人帮我找出以下代码中的问题。
背景:测试代码使用 4 个线程添加两个数组 input1 和 input2 并将结果存储在输出中。问题是其中一个线程无法正确执行,其中一个线程的输出缓冲区随机显示“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);
}