Multithreading 添加两个不使用pthread的数组
你能帮我找出下面代码中的问题吗 背景:测试代码添加了两个数组,input1和input2,并使用4线程将结果存储在输出中。 问题是其中一个线程无法正确执行,其中一个线程的输出缓冲区随机显示0。非常感谢您的帮助Multithreading 添加两个不使用pthread的数组,multithreading,pthreads,symbolicc++,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];
#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);
}
我已经找到了问题的根本原因。。。 &i给出了未知的结果,因为我的内存将被++i覆盖,线程\u id[0]在创建线程时得到不同的值。。。所以你应该有一个专用的内存,这样就不会被++i重写 &我是问题所在
int result = pthread_create(&thread_id[i], NULL, Addition, &i);
要解决此问题,请替换为共享的_数据[i]。。。。
int result=pthread_create&thread_id[i]、NULL、Addition和shared_data[i];
共享的_数据是由4个元素组成的数组。。像这样
int shared_data[4] = {0,1,2,3};