尝试使用pthreads访问共享数据阵列时无法访问错误的内存地址

akhil28288

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

    }

提前致谢!

贾罗德42
*data[i]->array = *array;

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

struct a { int* array; }

然后,只需复制指针。

data[i]->array = array;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

gdb无法访问内存地址错误

C - 无法访问内存地址

rMATS 错误“无法访问共享库”

无法访问共享数据量

在C中访问共享内存时出现分段错误

尝试从Docker容器访问共享内存时将“权限拒绝”,即使--ipc设置为“主机”

尝试访问数据连接器 API 时出现“无法访问 API 产品”错误

使用 suid 安装 debian linux 头文件后无法访问共享库

从汇编代码调用的 Rust 函数访问共享内存时的一般保护错误

使用信号访问共享内存到子进程

通过printf()访问内存地址值时出现AddressSanitizer错误

错误101:尝试更新时无法访问网络

OpenCL 访问共享本地内存

Python mmap访问共享的内核内存

当tryint在$ esp上查看内存时,Ubuntu gdb无法访问地址处的内存

使用内存地址访问结构的属性值

无法访问地址处的内存,尝试进行缓冲区溢出

'错误:java:无法访问java.util.function.Function'-尝试使用WebDriverWait时

尝试使用FragmentActivity时无法访问ActivityCompatApi23

无法使用Microsoft Graph API访问共享点列表-

无法使用python访问共享点列表

手动访问内存地址

共享内存地址

C套接字<错误读取变量:无法访问地址0xfffffffffffffffcc上的内存>

googleapis 驱动器无法访问共享驱动器文件

从广播接收者启动的asynctask中无法访问共享首选项

Windows Server 2003上的某些计算机无法访问共享

从辅助线程访问共享数据

尝试访问 Google Scripts 时出现“无法访问此页面”错误