Multi-thread programming-Win32 API-1

Source: Internet
Author: User

I. Introduction
---------------------------------------------------------------------

A process in Windows contains one or more threads. A thread is an execution path of a process. It contains an independent stack and CPU register status. Each thread shares all process resources, including open files, signal identifiers, and dynamically allocated memory. All threads in a process use the same 32-bit address space, and the execution of these threads is scheduled by the system.ProgramThe scheduler determines which thread can be executed and when to execute the thread. A thread has a priority level. A thread with a lower priority must wait until the task is executed by a thread with a higher priority level. On a multi-processor machine, the scheduler can put multiple threads on different processors for running, which can balance the processor tasks and improve the system running efficiency.

32-bit windows Win32 APIs provide interface functions required for multi-threaded application development. The MFC class library also encapsulates multi-threaded programming classes,

That is, we can use APIs provided by windows to Write multi-threaded programs, or use MFC to develop multi-threaded applications,

Therefore, you can select the appropriate tool based on the needs and features of the application during development.

If your application requires multiple tasks to be processed at the same time, multithreading is ideal.

2. Multi-Thread Programming Based on Visual C ++
---------------------------------------------------------------------
Multi-threaded programming is consistent with the principle supported by the MFC class library in Win32 mode. The main thread of the process can create a new

Thread. After the thread executes the task, the thread is automatically aborted. After the process ends, all threads are aborted. All active threads share the resources of the process

Source. Therefore, when programming, we need to consider a conflict when multiple threads access the same resource: When a thread is accessing a process object

, Another thread needs to change the object, which may produce incorrect results. Therefore, programmers must solve such conflicts during programming.

The following describes the multi-threaded programming process based on Win32.
------------------------------------------------------
1. Use Win32 functions to create and abort threads
-----------------------------------
The Win32 function library provides multi-threaded operation functions, including creating threads, suspending threads, and creating mutex.
First, create a new thread in the proper place of the main thread of the application or other active threads. The function used to create a thread is as follows:

Handle createthread
(Lpsecurity_attributes lpthreadattributes, // specifies the thread security attribute, which is ignored in Windows 95.
DWORD dwstacksize, // specifies the stack depth of the thread
Lpthread_start_routine lpstartaddress, // thread function
Lpvoid lpparameter, // specifies the 32-bit parameter transmitted to the thread during thread execution
DWORD dwcreationflags, // specifies the features of thread Creation
Lpdword lpthreadid // point to a DWORD variable and return the thread id value.
);

If creation is successful, the thread handle is returned. Otherwise, null is returned.

After a new thread is created, the thread starts execution.
If the create_suincluded feature is used in dwcreationflags, the thread will not be executed immediately, but will be suspended first,
Start the thread only after calling resumethread. In this process, you can call the function:

Bool setthreadpriority (handle hthread, int npriority );

To set the priority of the thread.

When the function of the thread returns, the thread stops automatically. If the thread is aborted during execution, you can call the function:

Void exitthread (DWORD dwexitcode );

If you stop a thread outside the thread, you can call the following function:

Bool terminatethread (handle hthread, DWORD dwexitcode );

Note: This function may cause system instability and the resources occupied by threads are not released.
Therefore, we recommend that you do not use this function.

If the thread to be aborted is the last thread in the process, the corresponding process should also be aborted after the thread is aborted.

2. Use Win32 functions to control the thread's access to shared resources
------------------------------------------
In the thread body, if the thread is completely independent and does not conflict with other threads in resource operations such as data access,
You can program the program in a single thread mode. However, this is often not the case in multithreading,
Threads often need to access some resources at the same time. For example, one thread is responsible for formula calculation, and the other thread is responsible for displaying the results,
Both threads must access the same result variable.
If you do not control the conflict, it is likely that the result is incorrect.

Conflicts between access to shared resources are inevitable, but we can use the following methods for Operation Control:

(1) set the mutex object of the thread to perform synchronization control in areas where conflicts may occur.
----------------------------------------------------------
First, create a mutex object and obtain the handle:

Handle createmutex ();

Then, at the beginning of the area where the thread may conflict (that is, before accessing shared resources ),
Call waitforsingleobject to pass the handle to the function. The request occupies the mutex object:

Dwwaitresult = waitforsingleobject (hmutex, 5000l );

After the shared resource is accessed, the usage of the mutex object is released:

Releasemutex (hmutex );

A mutex object can only be occupied by one thread at a time. When a mutex object is occupied by a thread,
If another thread wants to occupy it, it must wait until the previous thread is released to succeed.

(2) set the signal: Enable the signal before operating the shared resource. After the operation is completed, disable the signal. This is similar to processing mutex objects.
----------------------------------------------------------
First, create a signal object:

Handle createsemaphore ();

Or open a signal object:

Handle opensemaphore ();

Then, waitforsingleobject is called before the thread accesses shared resources.

After the shared resource is accessed, the consumption of the signal object is released:

Releasesemaphore ();

The signal object allows simultaneous access to resources shared by multiple threads. When creating an object, specify the maximum number of threads that can be accessed simultaneously.
After a thread successfully requests access, the counter in the signal object is reduced by one. After the releasesemaphore function is called, the counter in the signal object is incremented by one.
The counter value is greater than or equal to 0 and less than or equal to the maximum value specified at creation. Using Signal objects, we can not only control access to shared resources,
It can also be used during application initialization. Assume that an application sets the initial value of its counter to 0 when creating a signal object,
In this way, other threads are blocked and resources are protected. After Initialization is complete, call the releasesemaphore function to increase its counter to the maximum value,
For normal access.

(3) Use the status of the event object to access Shared resources by threads.
----------------------------------------------------------
Use the resetevent function to set the event object status to not allow the thread to pass; Use the setevent function to set the event object status to allow the thread to pass.

Events are divided into manual release and automatic release. If it is manually released, the event state will be handled according to the above two functions;
If it is automatically released, the event state is automatically cleared after a thread ends, allowing other threads to pass.

(4) set the exclusion zone.
----------------------------------------------------------
During asynchronous execution in the exclusion area, it can only share resource processing among threads of the same process.
Although the three methods described above can be used at this time, the use of the exclusion area method makes synchronization management more efficient;

First define a partition object of the critical_section structure, initialize the object before the process is used, and call the following function:

Void initializecriticalsection (lpcritical_section );

When a thread uses a exclusion zone, call the function:

Entercriticalsection or tryentercriticalsection

When occupying or exiting the exclusion zone is required, call the function:

Leavecriticalsection

Releases the occupation of objects in the exclusion zone for other threads.

Mutex objects, signal objects, and event objects can also be used for thread synchronization between processes.
When you create an object using the Win32 function, you can specify the Object Name and set the inheritance of the synchronization object in the child process.
The handle is returned. We can use the duplicatehandle function to copy the object handle,
In this way, each process can have a handle to the same object to implement thread synchronization between processes.
In addition, in the same process, we can use openmutex, opensemaphore, and openevent to get the handle of the synchronization object with the specified name.

The thread synchronization method asynchronously executed in the exclusion zone can only be used for sharing resource processing between threads of the same process,
However, this method is more efficient and easier to program.

 

Reference http://lijinshui.bokee.com/337857.html

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.