关于使用pthread_detach后出现Segmentation fault的问题

俞二侠 2020-07-15 01:47:41
我在函数中加入了线程分离,之后主线程进入while(1)循环,可是运行程序后报出的错误是Segmentation fault,请各位大佬帮我看看问题出现在哪里?谢谢了!!

void *mythread1(void)
{
int i;
pthread_detach(pthread_self());
for(i=0;i<10;i++)
{
printf("this is the 1 pthread,created by zhouzheng!\n");
sleep(1);
}
pthread_exit(NULL);
}

void *mythread2(void)
{
int i;
pthread_detach(pthread_self());
for(i=0;i<10;i++)
{
printf("this is the 2 pthread,created by zhouzheng!\n");
sleep(1);
}
pthread_exit(NULL);
}

int main()
{
int i=0;
int ret =0;
pthread_t id1,id2;
ret = pthread_create(&id1,NULL,(void*)mythread1,NULL);
if(ret) {
printf("Create pthread error!\n");
return 1;
}
ret = pthread_create(&id2, NULL, (void*)mythread2,NULL);
if(ret) {
printf("Create pthread error!\n");
return 1;
}
// pthread_join(id1,NULL);
// pthread_join(id2,NULL);
for(;;)
{
printf("this is main pthread\n");
sleep(1);
}
printf("Programme is end!\n");
return 0;
}

...全文
559 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
自信男孩 2020-07-15
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void *mythread1(void *)
{
int i;
pthread_detach(pthread_self());
for(i=0;i<10;i++)
{
printf("this is the 1 pthread,created by zhouzheng!\n");
sleep(1);
}
pthread_exit(NULL);
}

void *mythread2(void *)
{
int i;
pthread_detach(pthread_self());
for(i=0;i<10;i++)
{
printf("this is the 2 pthread,created by zhouzheng!\n");
sleep(1);
}
pthread_exit(NULL);
}

int main()
{
int i=0;
int ret =0;
pthread_t id1,id2;
//ret = pthread_create(&id1,NULL,(void*)mythread1,NULL);
ret = pthread_create(&id1,NULL,mythread1,NULL);
if(ret) {
printf("Create pthread error!\n");
return 1;
}
//ret = pthread_create(&id2, NULL, (void*)mythread2,NULL);
ret = pthread_create(&id2, NULL, mythread2,NULL);
if(ret) {
printf("Create pthread error!\n");
return 1;
}
// pthread_join(id1,NULL);
// pthread_join(id2,NULL);
for(;;)
{
printf("this is main pthread\n");
sleep(1);
}
printf("Programme is end!\n");
return 0;
}

供参考~

用这个代码试试
Simple-Soft 2020-07-15
  • 打赏
  • 举报
回复
把detach放到main里面

69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧