[Windows] thread-based discussion

Source: Internet
Author: User
Tags microsoft c

This series is intended to record the knowledge points of windwos threads, including thread basics, thread scheduling, thread synchronization, TLS, and thread pool.

Processes and threads

Understanding the thread is crucial. Each process has at least one thread. The process is the container of the thread, and the thread is the real execution body. The thread must run in the context of a process. The process has inertia. If all the threads in the process have ended, there is no need for the process to exist.

A process consists of the following two parts: 1. A process address space; 2. A process Kernel Object

A thread consists of the following two parts: 1. One thread stack; 2. One thread kernel object.

The thread overhead is much less than the process, so when solving programming problems, try to consider creating a thread in the current process rather than creating a new process. However, thread switching consumes a certain amount of CPU resources. Therefore, it does not mean that you can use threads without scruples to handle the problem.

 

Thread Lifecycle

Thread Creation

The system creates a thread kernel object;

The system reserves a thread stack space in the current process and allocates some physical memory;

Thread termination

Release all user objects owned by the thread (not quite understood)

Thread exitedCodeChange from still_active to real exit code

The thread kernel object changes to the trigger state.

If the thread is the last active thread in the process, the process will terminate

Use count of thread kernel objects minus 1

 

Thread creation and termination Methods

No matter what you useProgramming LanguageThe following APIs should be available for the final creation thread of any class library on Windows.

 
Handle winapi createthread, // specifies the initialization size of the thread stack. The value can be 0. The system selects a large _ in lpthread_start_routine lpstartaddress from the/stack link option and the value, // address of the initial function executed by the thread _ in_opt lpvoid lpparameter, // input the parameter _ in DWORD dwcreationflags of the initial function, // specify whether the thread can be scheduled immediately (that is, whether it is executed immediately). If it is create_suincluded, the system will suspend the thread running after initialization _ out_opt lpdword lpthreadid // thread ID, can be null );

It must be noted that the initial function always has the following function signature:

DWORD winapi threadproc (_ in lpvoid lpparameter );

This function returns the handle of the created thread kernel object. Unless the handle value is used for other purposes, you should immediately call closehandle to close the handle. Of course, closing the handle will not terminate the thread operation, but it can ensure that the thread even releases the thread kernel object after exiting.

The methods for terminating a thread include the return of the initial function of the thread, the call of exitthread by the thread to terminate itself, the call of terminatethread by the external thread, and the termination of a process containing the thread. Among them, except the first method, other methods are not recommended, because the thread does not exit normally and cannot guarantee the correct release of resources.

Using exitthread can also ensure that the system destroys the thread stack, but terminatethread cannot do so until the process is terminated;

 

Thread Initialization

Createthread causes the system to create a thread kernel object. The initial reference count of this object is 2.When the thread Exits normally, it will decrease once, And the thread handle will be closed once. When the reference count is 0, the operating system will release the kernel object.The pause count is set to 1, the exit code is set to still_active, and the object is set to not triggered.

The system allocates the thread Stack from the process address space, and writes pvparam and pfnstrataddr at a high level.

Each thread has its own set of CPU registers, called the thread context. Context reflects the CPU register status of the thread during the last execution. When a thread is rescheduled, the context stored in the kernel object is written back to the CPU register to restore the final state of the thread. This process is called "context switching ". The two most important registers are the stack register (SP) and command register (IP). SP points to the address of pfnstartaddr in the stack, and IP points to the rtluserthreadstart function (NTDLL. dll import ). Windows actually provides a context structure that describes the thread context, and provides the following two functions to obtain and set the context:

 
Bool winapi getthreadcontext (_ in handle hthread, _ inout lpcontext); bool winapi setthreadcontext (_ in handle hthread, _ in const context * lpcontext );

The context structure may be the only CPU-Related Structure on the Windows platform. Therefore, if you want to set this structure, you may need to consider different CPUs. If you do not set the context structure properly, it is likely to cause catastrophic consequences.

After the thread is fully initialized, the system will check the dwcreationflags in the createthread function. If the flag is not create_suincluded, the system will decrease the pending count to 0 so that the processor can schedule the thread.

 

Notes for running Microsoft C/C ++

Visual Studio comes with four C/C ++ runtime libraries for development and two. Net-hosted environments. Currently, all databases support multi-threaded development, and there is no Runtime Library specifically for single-threaded development (the emergence of the C \ c ++ Runtime Library is earlier than that of the multitasking operating system, therefore, a single-threaded Runtime Library is available at that time.)

library name description
libcmt. lib static link release version of the library
libcmtd. lib static link debugging version of the library
msvcrt. lib Import to database, used to dynamically link the release version of msvcrxxx. dll library
msvcrtd. lib Import to database, used to dynamically link the debugging version of msvcrxxxd. dll library (default)
msvcmrt. lib Import to warehouse, user-managed/Local Code hybrid
msvcurt. lib import the database and compile it into pure msil Code

Always use _ beginthreadex of the Runtime Library to create a thread, and use _ endthreadex to replace exitthread.

 

Thread suspension, recovery, and sleep

As discussed above, the thread can be set to suspend during creation. We can use the following two functions to suspend and resume threads:

 
DWORD winapi suspendthread (_ in handle hthread); DWORD winapi resumethread (_ in handle hthread );

Call suspendthread to increase the thread Kernel Object suspension count, which can be suspended multiple times, and the corresponding can also be restored multiple times. In addition, there is no perfect function for "suspending processes", because the only method is to traverse and suspend all threads in the process. However, if a new thread is created during the traversal process, or the thread just traversed is destroyed. Therefore, be very careful when trying to "suspend the process" and try to avoid it.

Use the following function to suspend the current thread for a period of time

Void winapi sleep (_ in DWORD dwmilliseconds );

Labor fruit, reproduced please indicate the source: http://www.cnblogs.com/P_Chou/archive/2012/06/10/basic-of-thread.html

Related Article

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.