Advanced Programming for UNIX environments: the exit relationship between the main thread and the child thread

Source: Internet
Author: User

We often create additional new threads in one thread, and if the main thread exits, will it affect the new threads it creates? Let's talk about it here.

1, the main thread waiting for the new line enters upgradeable end exit, the main thread after the exit. Normal execution.

Sample code:

#include <stdio.h>  
#include <stdlib.h>  
#include <pthread.h>  
#include <unistd.h >  
#include <sys/types.h>  
      
pthread_t ntid;//thread id  
      
void printids (const char *s)  
{  
        pid_t pid ;  
        pthread_t Tid;  
        PID = Getpid ();  
        Tid = Pthread_self ();  
        printf ("%s pid%u tid%u (0x%x) \ n", s, (unsigned int) PID,  
                        (unsigned int) tid, (unsigned int) tid)  
;  
      
void *thrfun (void *arg) {  
        //sleep (1);//makes the mainline enters upgradeable exit  
        printids ("New Thread");  
      
        return ((void *) 0);  
}  
      
int main () {  
        int err;  
        Err = Pthread_create (&ntid,null,thrfun,null);  
      
        if (Err!= 0)  
                perror ("Pthread_create");  
        Printids ("main thread");  
      
        Sleep (1);//Waiting for new line enters upgradeable end  
      
        exit (0);  
}

Run Result:

huangcheng@ubuntu:~$./a.out
main thread pid 2344 tid 3077813952 (0xb773b6c0)  
new thread pid 2344 tid 3077811056 ( 0XB773AB70)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.