我在函式中加入了執行緒分離,之后主執行緒進入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;
}
uj5u.com熱心網友回復:
把detach放到main里面uj5u.com熱心網友回復:
#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;
}
供參考~
用這個代碼試試
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/27639.html
標籤:C語言
上一篇:重定義為什么不報錯
