Methods for inter-thread communication include: 1. Global variables, memory sharing between threads in the process, which is a common communication method and interaction method; 2. Message message mechanism; 3. CEvent object, CEvent is An object in MFC can achieve communication between threads by changing the triggering status of CEvent.
There are three main methods of multi-thread communication:
1. Global variables
Memory sharing between threads in the process is a common communication method and interaction method.
Note: It is best to use volatile when defining global variables to prevent the compiler from optimizing this variable.
2. Message message mechanism
There are two main interfaces for commonly used Message communication: PostMessage and PostThreadMessage.
PostMessage is the thread sending messages to the main window. Send a message. PostThreadMessage is the communication interface between any two threads.
2.1.PostMessage()
Function prototype:
B00L PostMessage (HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);
Parameters:
hWnd: The handle of the window whose window program receives messages. Two values with specific meanings are available:
HWND.BROADCAST: The message is sent to all top-level windows of the system, including invalid or invisible non-owning windows and overwritten windows
and pop-up windows. Messages are not sent to child windows.
NULL: The operation of this function is the same as calling the PostThreadMessage function with the parameter dwThread set to the identifier of the current thread.
Msg: Specifies the message to be sent.
wParam: Specifies additional message-specific information.
IParam: Specify additional message-specific information.
Return value: If the function call is successful, the return value is non-zero: If the function call fails, the return value is zero.
MS also provides the SendMessage method for communication between messages, SendMessage(). The difference between it and PostMessage is:
SendMessage is synchronous, while PostMessage is asynchronous. SendMessage must wait until the sent message is executed before returning.
2.2.PostThreadMessage()
The PostThreadMessage method can send messages to the specified thread.
Function prototype: BOOL PostThreadMessage(DWORD idThread,UINT Msg,WPARAM wParam, LPARAM lParam);
The parameters are basically the same as PostMessage except for ThreadId.
The target thread receives messages through the GetMessage() method.
Note: When using this method, the target thread must already have its own message queue. Otherwise, the ERROR_INVALID_THREAD_ID error will be returned. You can use
PeekMessage() to create a message queue for a thread.
3. CEvent object
CEvent is an object in MFC. You can change the triggering state of CEvent to achieve communication and synchronization between threads.
The above is the detailed content of Several methods of communication between threads. For more information, please follow other related articles on the PHP Chinese website!