我有一个带有两个线程的 pthread 程序。第一个线程写入 Array[0 - 196607],第二个线程写入 Array[196608 - 393215]。
我在访问数组元素 [33779 到 393215] 时收到“无法在地址访问内存”错误。因此,我遇到了段错误。有人可以帮助我如何继续调试这个问题吗?
我的下一个问题是,当我的线程写入同一数组的不同地址位置时,我是否需要对它们使用锁?
相关代码为
main.cpp 的内容
#include <stdio.h>
#include <stdlib.h>
#include "a.cpp"
int *array;
int main() {
array = new int[393216];
foo(array);
return 0;
}
a.cpp 的内容
#include <pthread.h>
#include <stdlib.h>
struct a {
int array[];
};
pthread_mutex_t mutex;
void *funcname (void* param) {
struct a *data = (struct a*) param;
int index = 33779;
pthread_mutex_lock(&mutex);
data->array[index] = 1;
pthread_mutex_unlock(&mutex);
}
void foo (int array[]) {
struct a* data[2];
pthread_mutex_init(&mutex, NULL);
pthread_t threads[2];
for ( int i = 0 ; i < 2 ; ++i) {
data[i] = (struct a*)malloc (sizeof(struct a));
*data[i]->array = *array;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create (&threads[i], NULL, funcname, data[i]);
}
for ( int i = 0 ; i< 2; ++i)
pthread_join( threads[i], NULL );
}
提前致谢!
最佳答案
*data[i]->array = *array;
只复制第一个元素。 你可以使用
struct a { int* array; }
然后,只需复制指针。
data[i]->array = array;
关于c++ - 尝试使用 pthreads 访问共享数据数组时出现错误,无法访问内存地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18329742/