In-depth parsing of parent and child threads

Source: Internet
Author: User

Speaking of multithreading, we can talk about a lot of interesting topics related to it, such as child thread relationships, parent-child thread relationships, thread synchronization Asynchronization, and so on. What I said today, it is an interesting phenomenon about Parent and Child threads.

 

First, I would like to raise a question: "Will the sub-thread exit after the parent thread ends in a multi-threaded application ?", This article will focus on this issue and analyze the lifecycle of parent and child threads in windows and their relationships.

 

We know that no matter what programming language you use, but when we program in windows and use a platform-related library, No matter what function we use to create a thread, the final result is that our code will call createthread to create a thread. Of course, this job is completed by the library encapsulation you are using, you don't have to worry about how it works. After the task of a thread is completed and it must be completed, our code will call exitthread or teriminatethread to terminate the thread running. The previous function is generally used to terminate itself, the latter function can terminate any thread, and is mostly used to terminate other threads.

 

In "Windows core programming", we will tell you that, in general, we should try to make the thread return by itself rather than use exitthread or teriminatethread to forcibly terminate the thread, do not end the thread by terminating the process containing the thread before the end of the thread. Why?

 

Under normal circumstances, this is the best way to handle the normal return of the thread function. If the thread function returns normally, it will process the following four tasks:

1. All the C ++ objects created in the thread functions are destructed normally through their destructor.

2. The operating system correctly releases the memory used by the thread stack.

3. The operating system sets the exit code of the thread as the return value of the thread function.

4. The system reduces the usage count of the thread kernel object.

 

When the thread is terminated, it will handle the following tasks:

1. All user object handles owned by the thread will be released. In Windows, most objects are owned by processes that contain the thread for creating these objects. However, a thread has two user objects: Windows and hooks. When a thread ends, the system will automatically destroy any windows created or installed by the thread, and uninstall any hooks created or installed by the thread. Other objects will be destroyed only when the thread-owning process is terminated.

2. the exit code of the thread changes from still_active to the Code passed to exitthread or terminatethread.

3. The state of the thread kernel object changes to the trigger state.

4. If the thread is the last active process of the process, the system determines that the process is terminated.

5. Reduce the usage count of the thread kernel object to 1.

Therefore, in order to recycle the resources occupied by various threads and make the thread functions return normally, this is the best solution.

 

The Parent and Child threads are explained below. There are two scenarios for parent and child threads:

The first type is that the parent thread is the main thread of the process, and the Child thread is created by the main thread;

The second case is that the parent thread creates a sub-thread for the main thread of the process, and this sub-thread creates a sun-thread, which is mostly called a child thread.


For the problem we raised earlier, Let's first look at the second case. Assume that the main thread is A, thread B is created, and thread C is created for thread B. Now, if thread B is terminated, will thread C be terminated? Let's take a look at the prototype of createthread:

HANDLE WINAPI CreateThread(
  __in          LPSECURITY_ATTRIBUTES lpThreadAttributes,
  __in          SIZE_T dwStackSize,
  __in          LPTHREAD_START_ROUTINE lpStartAddress,
  __in          LPVOID lpParameter,
  __in          DWORD dwCreationFlags,
  __out         LPDWORD lpThreadId
);

Here, we are concerned with the first two parameters,LpthreadattributesIt indicates the Default Security Attribute of the thread kernel object. Generally, null is passed in, indicating that the system has the default security attribute. To make the sub-thread inherit the object handle of this thread, you must specify this structure. I will not elaborate on how to specify it here. What we want to know is that if the C thread inherits the object handle of the B thread, will the B thread end and the C thread end? We learned from the management of kernel objects by the operating system that if the C thread inherits the object handle of the B thread, the reference count of this object will increase, and when the B thread ends, this count will decrease, but it should be noted that this is not a zero, but a decrease. The operating system recycles resources by checking the reference count of kernel objects. If it is not zero, it will not be recycled, therefore, even if the C thread inherits the object handle of the B thread, the C thread will survive when the B thread ends.

 

Let's look at the second parameter.DwstacksizeIt indicates the address space used by the specified Thread stack. When we notice that the address space is allocated not on the parent thread, but on the physical storage of the system, we already understand that this space is irrelevant to the parent thread.

 

The preceding two methods are available. Since the C thread we created does not use any resources of the B thread, that is, the C thread created by the B thread is independent of each other after being created, in this case, if the B thread is terminated, the C thread will not end when the thread function does not return.

 

Next we will discuss the first case: the parent thread is the main thread of the process, and the Child thread is created by the main thread. This situation is complicated. According to "in-depth analysis of Windows operating system", Windows itself has no process concept at the system level. Looking at this part of the source code, we will find that CreateProcess actually calls createthread. This indicates that the main thread can be a conceptual process. As for the address space, it is only determined by a data structure, or it is irrelevant to the process concept we understand. Windows core programming is also cloud. When the entry point function (winmain, wwinmain, main, or wmain) of the main thread returns, it will return the startup code in the C/C ++ runtime, it can correctly clear all the C-runtime resources used by the process. After resources are released in the C runtime, the C Runtime startup Code explicitly calls exitprocess and passes the value returned by the entry function to it. This explains why the entire process can be terminated only when the main thread enters the vertex function to return. Note that any other thread running in a process terminates the process along with the process.

 

The msdn document states that the process will not be terminated until all threads stop running. This is true for the operating system. However, C/C ++ uses different rules for applications during runtime, by calling exitprocess, so that the C/C ++ runtime startup code can ensure that the process stops running when the main thread returns from its entry point function, regardless of whether there are other threads in the process. However, if you call exitthread in the entry point function instead of calling exitprocess or simply returning, the main thread of the application stops running. However, if at least one thread in the process is still running, the process will not stop running.

 

In another special case, if a deadlock occurs in a sub-process, the sub-process cannot exit, and the whole process cannot exit. This is why sometimes our program has exited (at least the interface has been closed), but there is still a reason for the process of this application in the task manager.

After figuring out the answer to the question, you can finally breathe a sigh of relief. It is worth exploring for a small question, a university question!

References: Msdn in-depth analysis of Windows operating system, Windows core programming

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.