Windows multithreaded Programming Summary __ Programming

Source: Internet
Author: User
Tags inheritance terminates
Summary of Windows multithreaded programming

Keywords: multithreaded thread pool Kernel object 1 kernel objects 1.1 Kernel Object concept

A kernel object is a memory block allocated by the kernel, which is a data structure that represents the various characteristics of the kernel object. and can only be accessed by the kernel. Applications that require access to kernel objects need to be performed through the functions provided by the operating system and cannot directly access kernel objects (Windows considers security considerations).

Kernel objects are created by create*, which returns a handle that identifies kernel objects that can be used within the scope of the creation process and cannot be passed to other processes. 1.2 Count of kernel object usage

Since the owner of the kernel object is the kernel, not the process, it is up to the kernel to decide when to undo the kernel object, and the kernel makes this decision based on whether the kernel object is still being used. So how do you tell if a kernel object is being used? You can pass the "use Count" attribute of the kernel object, and once that value becomes 0, the kernel can release the object. 1.3 Create kernel Objects 1.3.1 Process and handle table

Each process, when initialized, is assigned a handle table that stores only the handle of the kernel object and does not store the handle of the user object. The detailed structure of the handle table Microsoft did not publish, but roughly contains three content: Kernel object handle, kernel object address, access mask flag.

Why does Microsoft want to set the handle of a kernel object to process related? Reasons are:

L different processes have different access rights to kernel objects, and it is necessary to distinguish between

L If the handle is global, a process can control the handle of another process and break the handle of another process.

1.3.2 Creating kernel objects and operating system internal mechanism

Use the Createsomeobject function to create a kernel object. When the function is called, the kernel assigns a block of memory to the object and initializes it, then the kernel scans the process's handle table, initializes a record, and places it in the handle table. 1. Internal mechanisms for using kernel objects in 3.3 processes

Assuming that function f uses a kernel object with a parameter of Handle1, the function internally needs to find the handle table for the process, find the record for the parameter handle, and then use the kernel object. 1.4 Close Kernel Object

Regardless of how the process creates a kernel object, you should end access to the operating system declaration to the OS by using bool CloseHandle (HANDLE hobj) When you do not use the object. Why call it a statement. Because there may be other processes accessing the object at this point, the operating system may not immediately release the object. What the operating system needs to do is delete the kernel object's records from the process's handle table, and then examine the usage count of the kernel object to determine whether the object needs to be disposed.

1.5 Kernel-Object sharing

When it comes to sharing, the twin is sharing permissions. There are three ways to share Windows kernel objects: 1.5.1 Inheritance sharing (between parent-child processes)

You can use this method of sharing only if the process is a parent-child relationship. In particular, the inherited is the handle of the kernel object, the kernel object itself is not inheritable. To achieve this effect of inheritance, you need to do the following things:

L When a process creates a kernel object, it requires a security structure SA (security_attributes type to declare the object's access mode to the OS) as an argument. Inherited sharing requires that the member sa.binherithandle of the struct be set to true. The processing within the OS now sets the Access Mask field for the object in the handle table of the process to inheritable.

L set the Create parameter binherithandles to True when the child process (CreateProcess function) is created. Indicates that the child process being created can inherit all inheritable kernel objects in the parent process. The processing inside the OS is to copy the record in the parent process handle table to the handle table of the child process and use the same handle value, plus 1 for the kernel object's usage counter.

Special note: The kernel object that a child process can inherit is limited to the inheritable kernel objects owned by the parent process when it was created. When the child process is born, the parent process is able to get something to inherit, and the child process is not available. This requires careful use of inherited kernel objects in a child process to determine if the kernel object has been inherited.

By using the Sethandleinformation method, some properties of the kernel object handle can be modified at any time, there are two kinds of handles currently exposed, one is whether the handle can be inherited, and the other is whether the handle can be closed. 1.5.2 Share with the same name

Sharing with the same name does not require a parent-child relationship between shared processes. However, it is limited to whether the kernel object supports this sharing method. Whether the CREATE function that creates a kernel object contains pszname is whether the kernel object supports flags shared by the same name.

L Method One: When the Process1 through CreateObject (... "Somename") created a kernel object named Somename, Process2 also called CreateObject (... "Somename"), The action of the kernel at this time is to find an object that already exists someName1 in the global query, to add a ojbect record for the Process2 handle table, to use a handle that is indeterminate, and to add 1 to the reference counter of this object for Somename.

L Method Two: Process2 uses OpenObject (... "somename") to obtain a handle to the object named Somename. When using this open method, you need to provide a parameter for OS authentication to determine whether the kernel object can be accessed in the manner specified by the parameter. 1.5.3 Copy the handle of the kernel object share

Another way to share kernel objects across process boundaries is through DuplicateHandle to copy kernel object handles.

If you want to copy objects from Processs to PROCESST, the process that calls DuplicateHandle must have access to both processes, that is, the handle record that owns both process kernel objects in the handle table. 2 general concepts of threads 2.1 views

The L process is just a container of threads and never executes anything.

L threads are always created in a process

L thread executes code in the address space of the process

L Threads share all kernel objects in the process creation of 3 threads

1
2
3
4
5
6
7
HANDLE CreateThread (
Psecurity_attributes PSA,
DWORD Cbstack,
Pthread_start_routine Pfnstartaddr,
Pvoid Pvparam,
DWORD Fdwcreate,
Pdword Pdwthreadid);

"Windows core Programming" P124 that you should use a compiler-supplied thread to create a function, rather than using CreateThread directly. 3. Kernel behavior of 1CreateThread calls

After you call CreateThread, the OS does the following actions:

L Generate a thread kernel object

L Allocate stack space for threads within the process space

Because the thread's environment is the same as the environment of its process, the created thread can access all resources in the process, including all kernel objects in the thread. 4 thread pin dead 4.1 ways to terminate a thread:

L Thread function return (best use this way, can guarantee: Thread kind creates C + + object normal destructor; OS frees thread stack memory; The OS sets the exit code of the thread to the return value of the thread function; The system will decrement the usage counter for that thread's kernel object "If there are other references at this time ..., see description below." )

L Call ExitThread (C + + objects cannot be freed, so it is best not to use this method.) Also, if you want to call, you should call the compiler recommended, such as _endthread "Windows core programming P127".

L Call TerminateThread with other threads in the process (including the main thread) (the deactivated thread is not notified, cannot release resources, try to avoid this way.) In addition, this function is an asynchronous function, when returned, the thread is not guaranteed to have been revoked, if you want to observe whether the thread is revoked, you should use WaitForSingleObject

L The process that contains the thread terminates (this should be avoided) 4.2 behavior of the OS when a thread exits

All user objects within the L thread are freed.

L-thread exit code changed from still_active to ExitThread or TerminateThread code

L thread Kernel object status changed to "notified"

L If the thread is the last thread in the process, the OS treats the process as if it has terminated

L thread Kernel object's reference counter minus 1 (once the thread terminates, the other referenced thread kernel objects will not be able to handle the path's handle, but you can check to see if the hthread represented by calling GetExitCodeThread is terminated.) 5 Threads Sync 5.1 Causes of thread synchronization and solutions 5.1.1 Shared resource type: When multiple threads need access to the same resource, the thread's access to the resource is atomic in order to ensure that the resource is not compromised. 5.1.2-dependent: One thread waits for another thread to do something to perform _ can notify each other by means of a manual event. 5.2 thread synchronization type subdivision

Synchronization causes

Synchronization type

Sync Method Notes

Shared resources

Multiple threads add and subtract operations on shared variables

The family of interlocking functions: InterlockedExchangeAdd

Shared resources

Multiple threads assign actions to public variables, pointers

interlocking function family: InterlockedExchange, Interlockedexchangepoint

Shared resources

Multiple threads need to choose from the judgment of the public variables and pointers

The family of interlocking functions: InterlockedCompareExchange

Interlockedcompareexchangepointer

Shared resources

Complex data structure (not single value), not suitable for the family of interlocking functions

In the "Critical code" approach, the key code to note that 1, to be as fast as possible to prevent other waiting threads waiting for too long 2, thread waiting in the process of switching from user mode to kernel mode, consuming 1000 CPU cycles, longer time. 3, can only synchronize the threads in a single process)

InitializeCriticalSection;

EnterCriticalSection;

LeaveCriticalSection;

DeleteCriticalSection;

One way to handle thread synchronization

An abstraction of thread synchronization, in which the synchronization of threads is essentially dependent on the occurrence of some other event, using software to make an abstraction of the events on which they depend, will help with the simplicity of programming

CreateEvent

One of the important attributes of an event is "automatic" or "manual", and if it is automatic, after a thread has successfully waited for the notification state of the event with WAITXX, the event state immediately becomes "not notified", ensuring that only one thread is accessible to the resource at the same time.

In principle, it is not a thread synchronization category, but a kind of application method to wait**.

A kernel object that can be used as a timer, waitable timer

CreateWaitableTimer

SetWaitableTimer,

Cancelwaitabletimer

Shared resources

A set of threads competing against a set of resources of the same nature, the set of resources needs to be expressed to inform the threads whether they have free service to serve them and to implement the semaphore mechanism

Createsemaphore,releasesemaphore

Shared resources

A set of threads competing against a single resource requires a mechanism to ensure that only one thread of the same event can get resources. Implement in a mutex way

CreateMutex

ReleaseMutex

The difference from the key code is:

1. Allow synchronization between threads of different processes

2, kernel objects, user mode and kernel mode switching time requires more CPU overhead

Special Note: Waitforsingleobject/waitformultipleobject is a method of suppressing the thread itself, cooperating with the atomic changes of the "notification State" of the shared resource object or other objects on which it relies, in order to achieve the thread's contention for resources, The order of execution when interdependent, so as to achieve synchronization.

In summary: In fact, the thread synchronization mechanism of Windows is to provide a set of different circumstances of the resource contention approach. At the same time, the introduction of the WAITXX can bring many other benefits, or even partially alleviate the C + + language does not have the failure of the event mechanism, some of the java,c# to achieve the effect of the event mechanism for the implementation of Oberserve mode to make some contributions.

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.