Windows multi-thread programming

Source: Internet
Author: User

 

When the process ends, all threads terminate. The biggest problem with multithreaded programming is the access control of shared data.
Using Win32 APIs for programming has many advantages: Win32-based applications have low code execution and high running efficiency. However, it requires programmers to write more code and manage the resources provided to the program by all systems.

Create thread

HANDLECreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD
SIZE_T dwStackSize, // initial stack size
LPTHREAD_START_ROUTINE lpStartAddress, // thread function
LPVOID lpParameter, // thread argument
DWORD dwCreationFlags, // creation option
LPDWORD lpThreadId // thread identifier
);
Thread function prototype: DWORD WINAPIFun(LPVOID lpParamter );
Parameter description:
LpThreadAttributes: NULL uses the default security. It cannot be inherited by quilt threads. Otherwise, you need to define a struct to initialize its bInheritHandle member to TRUE.
DwStackSize: set the size of the initial stack, in bytes. If it is 0, the size of the stack space is the same as that of the thread that calls the function by default. In any case, Windows dynamically prolongs the size of the stack as needed.
LpStartAddress: pointer to a thread function. Format: @ function name, function name is not limited, but must be declared in the following column: dword winapi ThreadProc (LPVOID lpParam ), if the format is incorrect, the call will fail. However, lpStartAddress must be converted using LPTHREAD_START_ROUTINE as follows: (LPTHREAD_START_ROUTINE) MyVoid. MyVoid is declared as void MyVoid ();
LpParameter: a parameter passed to a thread function. It is a pointer to a structure and is NULL when no parameter is required.
DwCreationFlags: The following flag is recommended:
1. create_suincluded (0x00000004): Creates a suspended thread.
2. 0: activated immediately after creation
3. STACK_SIZE_PARAM_IS_A_RESERVATION (0x00010000): The dwStackSize parameter specifies the size of the initial reserved stack. Otherwise, dwStackSize specifies the submitted size. This tag value is not supported on Windows 2000/NT and Windows Me/98/95.
LpThreadId: id of the new thread to be saved.
Return Value:
If CreateThread is successful, a handle is returned, representing the new thread. Otherwise, a FALSE value is returned. If it fails, you can call GetLastError () to learn the cause.
The required parameter is lpStartAddress. The default value 0 or NULL can be used for other parameters.

 

Resume/suspend a thread

Dword winapi ResumeThread (_ in HANDLE hThread );
You can call this function to activate a suspended thread.
This function corresponds to SuspendThread. A thread can be used to create a suspended thread.
(DwCreationFlags parameter). The suspended thread is not executed until ResumeThread is called.

Set thread priority
BOOL SetThreadPriority (
HANDLE hThread, // handle to the thread
Int nPriority // thread priority level
);
The nPriority priority parameter can be set to the following parameters:
THREAD_PRIORITY_ABOVE_NORMAL is a level higher than the general priority.
THREAD_PRIORITY_BELOW_NORMAL is generally lower
THREAD_PRIORITY_HIGHEST is two levels higher than normal
THREAD_PRIORITY_IDLE
THREAD_PRIORITY_LOWEST is generally two levels lower
THREAD_PRIORITY_NORMAL general level
THREAD_PRIORITY_TIME_CRITICAL

Terminate thread

Termination in thread
If a thread calls the ExitThread function, it can terminate itself.
VOID ExitThread (DWORD dwExitCode );
DwExitCode: Specifies the thread release code.
Termination outside thread
BOOL TerminateThread (HANDLE hThread, DWORD dwExitCode );
Purpose:
Terminate a thread outside the thread to force terminate the thread.
Parameter description:
HANDLE htread: HANDLE of the terminated thread, which is a CWinThread pointer.
DWORD dwExitCode: Exit code.

Close handle

After CreateThread is successful, a handle of hThread will be returned, and the count of the kernel object is increased by 1. After CloseHandle, the reference count is reduced by 1. When it changes to 0, the system deletes the kernel object.
However, this handle does not fully represent this thread. It is only a "identifier" of the thread. The system and users can use it to perform necessary operations on the corresponding thread. If you no longer need to use this handle after the thread is successfully created, you can directly drop CloseHandle before the thread exits, but this does not affect the running of the thread.

Consequences of not executing CloseHandle:
If CloseHandle () is not used to reduce the reference count by 1 after the thread is executed, the leakage of the kernel object will occur during the process execution, which is equivalent to the leakage of the handle, but unlike Memory leakage, this will inevitably have a negative impact on system efficiency to a certain extent. However, remember that the system will automatically clear these resources when the process stops and exits. However, this practice is not recommended here. After all, it is not a good programming habit!
(Kernel objects may be leaked when the application is running, but when the process stops running, the system can ensure that all content is correctly cleared. In addition, this is used for all objects, resources, and memory blocks. That is, when the process is terminated, the system will ensure that no objects are left .)

Determine the program running status
The thread end code can be known by calling GetExitCodeThread.
BOOL GetExitCodeThread (HANDLE hThread, LPDWORD lpExitCode );

Synchronization and mutex

Win32 API provides a set of wait functions that can be executed by threads. These wait functions generate signals for one or more synchronization objects in their parameters, or return results after the specified wait time is exceeded. When waiting for not returned results, the thread is in the waiting state. At this time, the thread consumes only a small amount of CPU.
The most common wait functions are:
Dword winapi WaitForSingleObject (
_ In HANDLE hHandle,
_ In DWORD dwMilliseconds
);
Parameters:
HHandle: object handle. You can specify a series of objects, such as Event, Job, Memory resource notification, Mutex, Process, Semaphore, Thread, and Waitable timer.
When the handle is closed while the wait is still pending, the function action is undefined. This handle must have the SYNCHRONIZE access permission.
DwMilliseconds: scheduled time interval, in milliseconds (MS). If a non-zero value is specified, the function is waiting until the object marked by hHandle is triggered or the time has elapsed. If dwMilliseconds is 0 and the object is not triggered, the function will not enter a waiting state and it will always return immediately. If dwMilliseconds is INFINITE, the function returns only when the object is triggered.

Return Value:
WAIT_ABANDONED 0x00000080: When hHandle is mutex, this return value is returned if the thread with mutex does not release the core object at the end.
WAIT_OBJECT _ 0 0x00000000: the core object has been activated.
WAIT_TIMEOUT 0x00000102: wait for timeout
WAIT_FAILED 0 xFFFFFFFF: an error occurs. You can get the error code through GetLastError.

 

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.