日期:2014-05-16  浏览次数:20596 次

进程中创建的线程,线程如何终止的
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);之后不是去执行线程的代码了吗?
在线程中死循环的话,怎么又返回到进程中去了。 


------解决方案--------------------
int pthread_kill(pthread_t thread, int sig)
------解决方案--------------------
然后pthread_cancel
------解决方案--------------------
因为主线程退出相当于进程exit。

所以主线程最好pthread_join阻塞在那里,线程最好主动退出,不主动就cancel之再join。
------解决方案--------------------
C/C++ code
#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;
}