【问题标题】:Threads passing arguments传递参数的线程
【发布时间】:2014-10-05 06:24:45
【问题描述】:
#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);
}

我正在尝试使用结构将数据传递给线程.....但是我总是收到分段错误错误....谁能告诉我我的代码有什么问题..

【问题讨论】:

  • 在假设您错误地设置线程之前,请考虑一下,如果您丢弃了线程,并且只是 调用 summulp 设置正如您拥有它(或视情况而定),您可能会得到相同的结果(在火焰球中坠毁)。简而言之,您忘记了(或从未了解过)指针在 C 中是如何工作的。

标签: c multithreading struct pthreads


【解决方案1】:

您遇到分段错误,因为您没有为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);
}

【讨论】:

【解决方案2】:

您遇到了段错误,因为 p 已初始化为 0。你没有给它分配任何东西。

【讨论】:

  • @alk 是一个全局变量,它按照 C 标准初始化为空指针。
猜你喜欢
  • 1970-01-01
  • 2011-08-04
  • 2011-02-18
  • 2012-10-19
  • 2020-09-01
  • 2015-03-08
  • 2014-01-05
相关资源
最近更新 更多