进程中创建的线程,线程如何终止的

gfdsg_____ 2011-10-12 09:22:08
i am one thread!
i am one thread!
i am one thread!
i am one thread!
i am one thread!
i am one thread!
back to the main funciton!
i am the main!
[root@Robot 2]#
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <fcntl.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <sys/ioctl.h>
7 #include <syspes.h>
8 #include <sys/stat.h>
9 #include <errno.h>
10 #include <pthread.h>
11
12 void *my1(void)
13 {
14 int fd;
15 while(1)
16 {
17 printf("i am one thread!\n"); 18 }
19 }
20
21 int main(void)
22 {
23 pthread_t id1;
24 pthread_create(&id1, NULL, (void *)my1, NULL);
25 printf("back to the main funciton!\n");
26 printf("i am the main!\n");
27 return 0;
28 }
为什么我在线程中执行while(1)这个循环,最后线程自己退出了呢??认为线程把进程的资源用的差不多了,进程把线程给终止了,这样子对吗??程序执行到pthread_create(&id1, NULL, (void *)my1, NULL);之后不是去执行线程的代码了吗?
在线程中死循环的话,怎么又返回到进程中去了。
...全文
154 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq120848369 2011-10-12
  • 打赏
  • 举报
回复
#include <iostream>
#include <pthread.h>
#include <cstdio>
using namespace std;

void* pFunc(void*)
{
while(1)
{
cout<<"1"<<endl;
}

return NULL;
}

int main()
{
pthread_t pdID;
void *ret=NULL;

if(pthread_create(&pdID,NULL,pFunc,NULL)!=0)
{
perror("create");
return 1;
}

if(pthread_cancel(pdID)!=0)
{
perror("cancel");
return 3;
}

if(pthread_join(pdID,&ret)!=0)
{
perror("create");
return 2;
}

cerr<<"pthread ret"<<endl;

return 0;
}
qq120848369 2011-10-12
  • 打赏
  • 举报
回复
因为主线程退出相当于进程exit。

所以主线程最好pthread_join阻塞在那里,线程最好主动退出,不主动就cancel之再join。
haixuelang 2011-10-12
  • 打赏
  • 举报
回复
然后pthread_cancel
haixuelang 2011-10-12
  • 打赏
  • 举报
回复
int pthread_kill(pthread_t thread, int sig)
gfdsg_____ 2011-10-12
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <pthread.h>

void *my1(void)
{
int fd;
while(1)
{
sleep(1);
printf("i am one thread!\n");
}
}

void *my2(void)
{
int fd;
while(1)
{
sleep(2);
printf("i am two thread!\n");
}
}
主线程和线程交替运行,说明了,开始我的那个程序,是因为主线程结束了,我的错误在于认为,创建了线程先去执行线程。他们应该说差不多是同步执行的。所以那个死循环在主线程执行完了,自然也就解说了。
gfdsg_____ 2011-10-12
  • 打赏
  • 举报
回复
各位说的对啊,开始我理解错了,应该是,创建线程之后,进程和线程都会执行的,我开始认为线程执行完了,才会执行进程,其实是都有执行的,pthread_join等待线程
jihen 2011-10-12
  • 打赏
  • 举报
回复
线程创建的时候有线程号,用来管理的,你可以发送信号来结束该线程.
念茜 2011-10-12
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 dd_zhouqian 的回复:]

1.线程是依赖于进程存在的,进程退出了,线程也就随之销毁了。
2.等待线程退出可以通过调用pthread_join函数来达到效果。
[/Quote]
lz进程和线程有点混淆了
dd_zhouqian 2011-10-12
  • 打赏
  • 举报
回复
1.线程是依赖于进程存在的,进程退出了,线程也就随之销毁了。
2.等待线程退出可以通过调用pthread_join函数来达到效果。

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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