c - 线程传递参数

标签 c multithreading struct pthreads

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>

pthread_t id1,id2;
struct arg{int a[2];}*p;

void *sum(void *args)
{
    struct arg *b=((struct arg*)args);
    printf("hello:%d%d",b->a[0],b->a[1]);
}

void *mul(void *args)
{
    struct arg *c=((struct arg*)args);
    printf("hi:%d%d",c->a[0],c->a[1]);
}

main()
{
    int err1,err2;
    p->a[0]=2;
    p->a[1]=3;
    err1=pthread_create(&id1,NULL,&sum,(void*)p);
    err2=pthread_create(&id2,NULL,&mul,(void*)p);sleep(5);
}

我正在尝试使用结构将数据传递给线程......但我总是遇到段错误......任何人都可以告诉我我的代码有什么问题......

最佳答案

您遇到段错误是因为您没有为p 分配内存;它尝试将值分配给内存地址 0,这会导致段错误。

尝试使用 malloc 分配内存:

main()
{
int err1,err2;
struct arg *p=(struct arg *)malloc(sizeof(struct arg));
p->a[0]=2;
p->a[1]=3;
err1=pthread_create(&id1,NULL,&sum,(void*)p);
err2=pthread_create(&id2,NULL,&mul,(void*)p);sleep(5);
}

关于c - 线程传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26200184/

相关文章:

c - 写入作为结构成员的字符数组

在 typedef 中使用指针调用变量

c - 如何在 C Win32 控制台应用程序中打印卡片套装字符?

c# SocketAsyncEventArgs 阻塞 ReceiveAsync 处理程序中的代码

java - 关于java中使用阻塞队列方法的生产者和消费者模式

java - 如何将包含结构的嵌套枚举从 Swift 转换为 Java?

c - 解释C程序的结果

c - 带有链表的无限循环

multithreading - 当线程被调度到不同的 CPU 内核上时,预期的内存语义(例如先读后写)会发生什么?

c++ - struct 成员默认初始化的区别