【问题标题】:Cannot Access Memory Adress at error when trying to access a shared data array with pthreads尝试使用 pthread 访问共享数据数组时无法访问内存地址错误
【发布时间】:2013-08-20 07:55:57
【问题描述】:

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

    }

提前致谢!

【问题讨论】:

  • 请看一些代码。
  • 为您的数据分配了足够的内存?
  • @joe:刚刚用代码更新了问题。谢谢
  • @Joachim Pileborg:是的,我有。
  • 您的代码示例应该简单、可编译并演示您的问题。仅仅把一个例子放在一起,有时也可以帮助你找到自己的问题! :-)

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


【解决方案1】:
*data[i]->array = *array;

只复制第一个元素。 你可以使用

struct a { int* array; }

然后,只需复制指针。

data[i]->array = array;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-21
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 2012-12-06
    • 1970-01-01
    • 2021-05-13
    相关资源
    最近更新 更多