首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C中的pthread_创建生成分段错误

C中的pthread_创建生成分段错误
EN

Stack Overflow用户
提问于 2021-12-06 11:13:36
回答 1查看 44关注 0票数 0

我的老师把这段代码放在他的幻灯片上,让我们试着运行它,但是当我运行时,我会出现“分段错误”错误。经过一些调试,我发现错误的来源是函数pthread_create(),如果我传递&attr参数,它会给我带来错误,但是如果我传递NULL,一切都可以正常工作。

我完全理解这段代码应该做什么,但我不明白它为什么会产生错误。

代码语言:javascript
复制
#include <pthread.h> 
#include<unistd.h> //threadAttr.c
void *my_fun(void *param){
    printf("This is a thread that received %d\n", *(int *)param);
    return (void*)3;
}
void main(){
    pthread_t t_id; pthread_attr_t attr;
    int arg=10, detachSTate;
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); //Set detached
    pthread_attr_getdetachstate(&attr,&detachSTate); //Get detach state
    if(detachSTate == PTHREAD_CREATE_DETACHED) 
        printf("Detached\n"); 
    pthread_create(&t_id, &attr, my_fun, (void *)&arg);
    
    printf("Executed thread with id %ld\n",t_id);
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); //Inneffective
    perror("");
    sleep(3);
    int esito = pthread_join(t_id, (void **)&detachSTate); 
    printf("Esito '%d' is different 0\n", esito);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-06 11:25:02

问题:

  1. void main() (通常)是一个无效的表单。这是int main().
  2. The代码没有调用pthread_attr_init。这似乎是分割错误的原因- strangely.

中的值未初始化,这将导致pthread_create的动作为

代码传递到一个指向pthread_join.

  • The代码中没有#include <errno.h>

#include <stdio.h>void*指针的指针

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70244585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档