How to end a thread in Windows

Source: Internet
Author: User

In Windows, the created thread has the following four termination methods:

1. thread function return

When a thread function returns, the thread is terminated. This method should always be used to end the running of the thread, because this is the only way to ensure that all thread resources are correctly cleared. If the thread returns successfully in this way, then:

1) All C ++ objects created in thread functions can be correctly revoked through their destructor

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

3) The system exits the thread.Code(Maintained in the kernel object of the thread) set as the return value of the thread function

4) The system will decrease the usage count of the thread Kernel Object

2. exitthread Function

You can call this function to forcibly terminate the running of the thread. This function will cause the operating system to clear all operating system resources used by this thread. However, C ++ resources (such as class objects) are not revoked. This method is usually a function used by windows to cancel a thread. Therefore, it is best to use method 1 to exit the thread, instead of calling this function to return.

3. terminatethread Function

Calling this function can also terminate the thread operation. However, unlike the exitthread function, the latter always revokes the called thread, while the former can cancel any thread. TerminatethreadIt is a function that runs asynchronously, that is, it tells the system that you want the thread to terminate the operation. However, when the function returns, the thread cannot be undone.If You Need To Know exactly that the thread has been terminated, you must call waitforsingleobject or similar functions. When methods 1 and 2 are used to cancel a thread, the memory stack space of the thread is also revoked. If terminatethread is used, the system does not cancel the running stack of the thread before the process that owns the thread stops running.

4.Process Termination thread

When a process is terminated, all threads in the process are terminated. Because the entire process has been disabled, all resources used by the process must have been cleared. Of course, this includes the stack space of all threads. UseThe exitprocess and terminateprocess functions force cancel the remaining threads in the process, just like calling terminataprocess from each remaining thread,Therefore, this also means that the application is correct.ProgramClearing does not happen, that is, the C ++ object destructor is not called, and the data is not transferred to the disk.

To sum up the above four methods, we should always use the first method to terminate the thread operation.

We can send a message to the subthread when the main thread is about to exit, or tell the subthread to exit automatically.

 

 

 

Today, I read some things about Windows multithreading. I can extract some things about closehandle here for future reference.

The two main sections in Windows core programming are as follows:

3.1.1 kernel object usage count
The kernel object is owned by the kernel, not by the process. In other words, if your process calls a function to create a kernel object and then your process stops running, then the kernel object may not be undone. In most cases, the object will be revoked, but if another process is using the kernel object created by your process, the kernel knows that, do not undo this object before another process stops using this object, It must be remembered that the existence time of the kernel object can be longer than the process for creating the object. .
The kernel knows how many processes are using a certain kernel object because each object contains a usage count. Counting is a common data member of all kernel object types. When an object is just created, its usage count is set to 1. Then, when another process accesses an existing kernel object, the Count increases by 1. When a process stops running, the kernel automatically determines the use count of all kernel objects that the process is still open. If the usage count of the kernel object is reduced to 0, the kernel will undo the object. This ensures that no kernel object is retained in the system when no process references this object.
3.2.2 disable kernel objects
No matter how the kernel object is created, specify to the system that the operation on the object will be terminated by calling c l o s e h a n d l E: this function first checks the handle table of the calling process to ensure that the index (handle) passed to it is used to identify an object that the process actually has no access. If the index is valid, the system can obtain the address of the data structure of the kernel object and determine the count data member in the structure. If the count is 0, the kernel removes the kernel object from the memory. If an invalid handle is passed to c l o s e h a n d l e, one of the two situations will occur. If the process runs normally, c l o s e h a n d l e returns fa l s e, while g e t l a s t e r o r _ I n va l I D _ H a n d l e is returned. If the process is troubleshooting an error, the system will notify the debugging program to exclude it.
Before c l o s e h a n d l e returns, it will clear the project in the Process Handle table. This handle is no longer valid for your process, you should not try to use it. The kernel object is cleared no matter whether it has been undone. After calling the c l o s e h a n d l e function, you no longer have access to the kernel object. However, if the count of the object is not decreased to 0, the object has not been revoked. This is okay, it just means that one or more other processes are using this object. When other processes stop using this pair (by calling c l o s e h a n d l e), the object will be revoked.
If I forget to call the C L O S E h a n d l e function, will there be Memory leakage? The answer is possible, but not necessarily. When a process is running, the process may leak resources (such as kernel objects ). However, when a process stops running, the operating system can ensure that any or all resources used by the process are released, which is guaranteed. For kernel objects, the system performs the following operations: when a process stops running, the system automatically scans the process handle table. If the table has any invalid items (that is, objects not closed before the process is terminated), the system will close these object handles. If the usage count of any of these objects is reduced to 0, the kernel will undo the object.
Therefore, kernel objects may be leaked when the application is running, but when the process stops running, the system will ensure that all content is correctly cleared. In addition, this situation applies to all objects, resources, and memory blocks. That is, when a process stops running, the system will ensure that the process will not leave any objects.

The following are comments from netizens:

Createthread starts a thread and generates a handle for you to manipulate it. If you don't want to use this handle, closehandle will shut it down.
Calling closehandle does not mean that the thread is terminated, but does not care about the status of the handle, and thus the thread of the sub-process cannot be controlled. If you need to care about it, you can try closehandle after the sub-process ends, but it must be closehandle.
The operating system kernel manages the life cycle of kernel objects. Applications Use closehandle to operate the reference count of kernel objects. When the reference count is reduced from 1 to 0, the kernel is responsible for destroying the corresponding kernel objects. Processes and threads both have a kernel object that corresponds to them. The operating system manages processes and threads through the kernel object.

My summary:

When you do not need to operate the created thread in the program, closehandle will drop. Even if the current count of that thread is 1, it will be reduced to 0 after you call closehandle, however, the created thread is not immediately revoked, but is canceled after the thread function is executed, or the whole process ends before the thread function is executed. It is not clear why the thread is not immediately revoked when the count is reduced to 0.

 

Today () I read "Windows core programming" and got some new ideas:

6.4: When createthread is called, The system creates a thread kernel object. The kernel object of this thread is not the thread itself, but the small data structure used by the operating system to manage the thread ................... This is the same as the relationship between processes and process kernel objects. 6.6: Call createthread to create a thread kernel object. The initial count of this object is 2 (the thread kernel object will not be revoked until the thread stops running and the handle returned from createthread is closed ).

According to the last article, I can explain my questions yesterday. ^_^

 

 

----------------------------------------------

1. Create a thread concept in a program

After a process is created, the system automatically allocates a main thread to the process. For the main function, after the main function is executed, the main thread exits, and the main thread exits, which also means that the process ends.

2. Reference count of threads, kernel objects, and kernel objects

1. There are several methods to create a thread. Here we will first learn how to use the createthread () function to create a thread. For the parameters and usage of this function, see msdn. If the thread is successfully created, the function returns a new thread handle. (According to Windows core programming, when a thread is created, the reference count of the thread kernel object is set to 1. Before the create function returns, the thread handle is opened, so the thread's kernel object reference count + 1)

========================================================== ========================================================== =

After createthread, the reference count of that thread is not 1, but 2.

Creating a new process causes the system to create a process Kernel Object
And a thread kernel object. At creation time, the system gives each object
An initial usage count of 1. Then, just before CreateProcess returns,
Function opens the process object and the thread object and places
Process-relative handles for each in the hprocess and hthread members
The process_information structure. When CreateProcess opens these objects
Internally, the usage count for each becomes 2. --- from Windows core programming

========================================================== ========================================================== =

3. closehandle () Usage

1. closehandel (threadhandle );
If a thread handle object is closed, it means that I no longer use the handle, and I am not interested in the handle, that is, I do not intervene in the thread corresponding to the handle. The thread does not end, And the thread itself is still running. If you need to perform some operations on this thread after createthread, such as changing the priority, waiting by other threads, and forcing termatethread, you need to save the handle and use closehandle () after use ().

2. Why is createthread () and closehandle () used together?

On the one hand, all kernel objects (including thread handle) are system resources and need to be paid back when they are used up. That is to say, closehandle must be disabled after use. Otherwise, your system's handle resources will soon run out. On the other hand, since the reference count of the thread kernel object after createthread () is 2, after closehandle () reference count-1, the reference count of the kernel object is not 0 and will not be released. Therefore, the thread is still running until the thread function is executed, the reference count is-1, and the thread ends.

You can also view this articleArticleHttp://hi.baidu.com/heiheijiushiwo/blog/item/02c29924e518e0318644f979.html

 

Inspiration:

1 windows core programming later

2. the system management thread uses the reference count of the kernel object in the thread. When the reference count is 0, the thread is disabled.

When createthread () is created, the reference count of the thread is 2.

When closehadle () is called, only operations on the thread are disabled, and the thread reference count is reduced by 1.

When the thread execution is complete, the reference count is reduced by 1 and normally ends at 0.

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.