Multithreaded programming 1-Getting Started

Source: Internet
Author: User
Tags getmessage message queue sleep function terminates

Common multithreaded API functions (go from http://blog.csdn.net/hcqi2004/article/details/3534853) CreateThread functions:

HANDLE CreateThread (

Lpsecurity_attributes Lpthreadattributes,

DWORD Dwstacksize,

Lpthread_start_routine Lpstartaddress,

LPVOID Lpparameter,

DWORD dwCreationFlags,

Lpdword Lpthreadid);

Parameters

Lpthreadattributes: A pointer to the structure of the security_attributes type. This parameter is ignored in Windows 98. In Windows NT, it is set to NULL, which means that the default value is used.

Dwstacksize, thread stack size, general = 0, in any case, Windows dynamically extends the size of the stack as needed.

Lpstartaddress, a pointer to a thread function, in the form of the @ function name, is malformed and cannot be called successfully.

Format of the thread function: DWORD WINAPI THREADFNC (LPVOID N); Note: The return value must be DWORD, must use WINAPI, function name THREADFNC can be arbitrarily named, function parameters must be LPVOID type.

Lpparameter: The parameter passed to the thread function is a pointer to the struct, nil when the parameter is passed.

dwCreationFlags: Thread flag, the following values are desirable
create_suspended create a suspended thread;
0 activated immediately after creation.

Lpthreadid: Save the ID of the new thread. The thread ID is a global variable that uniquely represents a thread in any process in the system. However, the handle cannot be obtained by ID.

return value:

The function succeeds, returns the thread handle, and the function fails to return FALSE.

Function Description:

Creates a thread.

It is generally not recommended to use the Createtheard function, but it is recommended to use the Begintheard function as defined in the system unit in the RTL library because it adds several protections in addition to creating a thread and an entry function.

CloseHandle function

BOOL CloseHandle (

HANDLE Hobject

);

Parameters

Hobject: Represents an open object handle

return value

TRUE: Successful execution,

FALSE: Execution failed and can be called GetLastError () to learn the cause of the failure.

Function Description:

Closes a kernel object. These include files, file mappings, processes, threads, security, and synchronization objects. After CreateThread succeeds, it returns a hthread handle, and after the count of the kernel object is added 1,closehandle, the reference count is reduced by 1, and when it becomes 0 o'clock, the system deletes the kernel object.

If after the thread executes, does not call the CloseHandle, during the process execution, will cause the kernel object leak, is equivalent to the handle leakage, but differs from the memory leak, this certainly may have the negative influence to the system efficiency to some extent. However, these resources are automatically cleaned up when the process finishes exiting.

GetExitCodeThread function:

Function: Gets the return value of an end thread

BOOL GetExitCodeThread (

HANDLE Hthread,

Lpdword Lpexitcode

);

Parameters:

Hthread: Handle to Thread object

Lpexitcode: Used to store the return value of the thread, if the thread ends, then the thread's end code is placed in the Lpexitcode parameter, and if the thread has not ended, the value of Lpexitcode is still_active.

return value:

If the function executes successfully, it returns a value other than 0, otherwise 0 (FALSE) is returned.

Function Description:

Gets the return value of the thread end.

ExitThread function

VOID ExitThread (DWORD dwexitcode);

Parameters

Dwexitcode: End code for thread

return value

no return value.

Description

This function is best used in C programs, in C + +, before return will call the destructor, call the function to end the thread, do not call the object's destructor and other automatic cleanup actions. When the function is called in the thread, the stack of the threads is retracted and all outstanding I/O operations are canceled. The dynamic connection libraries to which they are connected are also separated.

When the calling thread's function returns, the thread terminates automatically. This function can be called if it is necessary to terminate during the execution of a thread.

WaitForSingleObject function

DWORD WaitForSingleObject (

HANDLE Hhandle,

DWORD dwmilliseconds

);

Parameters

Hhandle: The handle to the event, in this case the thread handle;

Dwmilliseconds: The maximum time to wait. Time is up. If Hhandle does not return, the function is returned, and if the time is signaled the state returns WAIT_OBJECT_0, if the time exceeds the dwmilliseconds value but the time event or no signal state returns wait_timeout;

This value is 0, which means returning immediately

This value is infinite, which represents infinite waits.

return value

WAIT_OBJECT_0: Function returned successfully, signal status detected within the specified time

Wait_failed: Function failed, call GetLastError () to see more messages

Wait_timeout: Wait time is up, signal status has not been detected

Wait_abandoned: The thread that owns the mutex (mutex) does not release the mutex until the end

Function Description:

Set the waiting thread to Thread # # #, the executing thread is thread # # #, call WaitForSingleObject, set the first parameter of the function to be the handle of thread # #, then thread # # begins to sleep until thread # # ends.

Create multiple threads, and threads do not necessarily end in the order in which they were created. Call this function to only monitor a specified thread.

Waitformultipleobject function

DWORD WaitForMultipleObjects (

DWORD Ncount,

Const handle* Lphandles,

BOOL bWaitAll,

DWORD dwmilliseconds

);

Parameters

Ncount: Represents the number of elements of the handle data that Lphandles refers to.

Maximum capacity is maximum_wait_objects

Lphandles: Pointer to an array of object handles

bWaitAll: Whether to wait for all objects to have a signal

This value is false, and the return value minus WAIT_OBJECT_0 is the ordinal of the parameter Lphandles array. If more than one kernel object is set, the function returns only the one with the smallest ordinal.

This value is true,

The return value is WAIT_OBJECT_0, indicating that all events have been set.

The return value is wait_abandoned_0 to (wait_abandoned_0+ ncount–1), which indicates that an event has been discarded

Dwmilliseconds: The maximum time to wait. Time is up. If the hhandle does not return, the function is returned, and if there is a signal state in the specified time, the WAIT_OBJECT_0 is returned, if the time exceeds the Dwmilliseconds value but the event or signal state is returned wait_timeout;

This value is 0, which means returning immediately

This value is infinite, which represents infinite waits.

return value

WAIT_OBJECT_0: Function returned successfully, signal status detected within the specified time

Wait_failed: Function failed, call GetLastError () to see more messages

Wait_timeout: Wait time is up, signal status has not been detected

Wait_abandoned: The thread that owns the mutex (mutex) does not release the mutex until the end

Function Description:

When multiple kernel objects are triggered, WaitForMultipleObjects selects the return with the smallest ordinal. and waitformultipleobjects it only changes the state of the kernel object that makes it return. There is another problem here, if the object with the smallest number is frequently triggered, then the kernel object with the number larger than it will not be given the chance to be out of reason.

The lphandles array does not allow a gap to be generated, and when a handle is fired, you should remove the handle from the Lphandles array the next time you call the WaitForMultipleObjects function.

Windows message loop

The standard message loop in a Windows program looks like this:

while (GetMessage (&msg,null,0,0))

{

TranslateMessage (&MSG);

DispatchMessage (&MSG);

}

Call GetMessage () unless a message is actually entered in the message queue, otherwise it will not return. In the meantime, Windows is free to give CPU time to other programs.

Often it's important to go back to the main message loop, and if you don't, your window will stop redrawing, and there will be something users don't like. When you use the WaitForSingleObject or WaitForMultipleObjects function, it waits for an object to be fired, and you simply have no way to go back to the main message loop.

To solve this problem, the main message loop must be modified so that it can wait for the message at the same time or the core object to be fired, you must use the MsgWaitForMultipleObjects function.

msgwaitformultipleobjects function

DWORD MsgWaitForMultipleObjects (
DWORD Ncount,
Lphandle Phandles,
BOOL fWaitAll,
DWORD dwmilliseconds,
DWORD Dwwakemask
);

Parameters

Ncount: Number of handles in list

Phandles: Pointer to an array of object handles

fWaitAll: Whether to wait for all objects to have a signal,

Dwmilliseconds: The maximum time to wait. Time is up. If Hhandle does not return, the function is returned, and if the time is signaled the state returns WAIT_OBJECT_0, if the time exceeds the dwmilliseconds value but the time event or no signal state returns wait_timeout;

This value is 0, which means returning immediately

This value is infinite, which represents infinite waits.

Dwwakemask: Specifies which messages are observers (user input messages to observe), which can be:

Qs_allinput

Qs_hotkey

Qs_input

Qs_key

Qs_mouse

Qs_mousebutton

Qs_mousemove

Qs_paint

Qs_postmessage

Qs_sendmessage

Qs_timer

return value

WAIT_OBJECT_0: Function returned successfully, signal status detected within the specified time

Wait_failed: Function failed, call GetLastError () to see more messages

Wait_timeout: Wait time is up, signal status has not been detected

Wait_abandoned: The thread that owns the mutex (mutex) does not release the mutex until the end

Wait_to_completion: (for WaitForSingleObjectEx only), because an I/O completion operation is ready to execute, resulting in the return of the function.

WAIT_OBJECT_0 + ncount: Accepts messages specified by Dwwakemask

Function Description:

The iteration waits for a specific message in the specified thread, which is specifically defined for waiting for a message.

The MsgWaitForMultipleObjects function does not allow a gap in the handle array, so when a handle is fired, you should sort and compress the handle array before the next call to MsgWaitForMultipleObjects.

TerminateThread function

BOOL TerminateThread (

HANDLE Hthread,

DWORD Dwexitcode

);
Parameters

Hthread: Handle to Thread

Dwexitcode: End code for thread

return value

True: Function succeeded

False: Function failed

Function Description:

This function can be called if the thread is terminated outside the threads. After the function executes, the thread handle becomes the firing state and returns the end code.

The TerminateThread function is a dangerous function and should be used in the most unavoidable circumstances. Once this function executes successfully, the specified thread terminates execution immediately, so there may be a lot of end-of-processing work before it can be done, and the thread's stack is not released, so it may cause a memory leak---but the DLL for this line preempted has no chance of being notified to end the execution.

SuspendThread function

DWORD SuspendThread (

HANDLE hthread//thread handle

);

return value

Function succeeds, returns the previous pause count of the thread, or the previous hang number, otherwise returns 0x FFFFFFFF

Function Description:

Suspends the thread. A thread can be suspended multiple times. If a thread is suspended n times, the thread must also be restored n times before it can be executed.

ResumeThread function

DWORD ResumeThread (

HANDLE hthread//thread handle

);

return value

Function succeeds, returns the current suspend count of the thread, otherwise returns 0x FFFFFFFF

Function Description:

Wakes the thread.

Handle, which is the basis for the entire Windows programming. A handle refers to the use of a unique integer value, that is, a 4-byte (64-bit program is 8 bytes) Long value, to identify different objects in the application and similar objects in different instances, such as a window, buttons, icons, scroll bars, output devices, controls or files and so on. The application is able to access the information of the corresponding object through a handle, but the handle is not a pointer, and the program cannot use the handle to directly read the information in the file. If the handle is not in the I/O file, it is useless. A handle is a unique integer that Windows uses to flag or use in an application, and Windows use a large number of handles to identify many objects.

sleep function edit Function name: Sleep feature: Execution suspend for a period of time usage: void Sleep (DWORD dwmilliseconds); Use with top file in VC # include <windows.h> ( The sleep function holds the header file: WinBase.h) in the GCC compiler, the header file used differs depending on the GCC version # include <unistd.h>sleep () units in milliseconds, Sleep () The unit is seconds (if needed more precise can be in microseconds with usleep units) return value if the process/thread hangs to the time specified by the parameter returns 0, and if there is a signal interruption, returns the number of seconds remaining.

A simple threading example is created below

#include <iostream> #include <windows.h>using namespace std;//thread function DWORD WINAPI fun1proc (LPVOID lpparameter The parameter passed to the thread function is a pointer to the struct, null if the argument is not passed, and the//main function is the entry function address of the main thread, void Main () {HANDLE hthread1;hthread1=createthread (null The first parameter is NULL, set to the default security                  , 0//the second parameter to take the same stack size as the calling thread  , fun1proc//the third parameter specifies the address of the entry function for thread 1  , null// The fourth parameter is the parameter passed to thread 1  , 0//the fifth parameter is set to 0 so that the thread executes as soon as it is created  , null//the ID of the new thread for the sixth parameter  ); CloseHandle (HTHREAD1);//Close the handle to the new thread (there is no new thread to terminate the creation, just say the main thread is not interested in its reference) cout<< "main thread is running" <<endl; Sleep (//system) ("pause"); Entry function for thread 1 DWORD WINAPI fun1proc (LPVOID lpparameter) {cout<< "Thread1 is running!!! "<<endl;return 0;}

  

Multithreaded programming 1-Getting Started

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.