c++ - 尝试使用 pthreads 访问共享数据数组时出现错误,无法访问内存地址

标签 c++ debugging parallel-processing segmentation-fault pthreads

我有一个带有两个线程的 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/

相关文章:

C 编程 : seg faults, printf 和相关问题

parallel-processing - Gnu平行: nested parallelism

python - 进一步加快并行化进程

c++ - vector<>::maxsize() 的最大大小是多少?

c++ - 为什么我可以复制 unique_ptr?

c++ - 如何按类型从 std::tuple 获取元素

javascript - 如何在 Node.js 中组织多进程应用程序?

c++ - 打印出 std::string 崩溃并出现段错误

ruby-on-rails - rails 不在调试器处停止的原因

c# - 以编程方式将调试器附加到在另一个应用程序域中运行的代码