Joke Collection Website - Public benefit messages - What are the communication methods between threads?

What are the communication methods between threads?

There are three main methods for multithreading communication:

1. global variable

The memory between threads in a process is shared, which is a common way of communication and interaction.

Note: it is best to use volatile when defining global variables in case the compiler optimizes this variable.

2. Message message mechanism

There are two common interfaces for message communication: PostMessage and PostThreadMessage.

PostMessage sends a message to the thread's main window. PostThreadMessage is a communication interface between any two threads.

2. 1.PostMessage()

Functional prototype:

B00L PostMessage(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM LPARAM);

Parameters:

The handle of the window where the window program receives the message. You can take two values with specific meanings:

HWND。 Broadcast: The message is sent to all the top windows of the system, including invalid or invisible windows and covered windows that do not belong to them.

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, and the parameter dwThread is set as the identifier of the current thread.

Msg: Specifies the message to be sent.

WParam: Specifies additional information specific to the message.

IParam: Specifies additional information specific to the message.

Return value: if the function call is successful, a non-zero value is returned; If the function call fails, the return value is zero.

MS also provides the SendMessage method SendMessage () for inter-message communication, which is different from PostMessage:

SendMessage is synchronous, while PostMessage is asynchronous. SendMessage must wait for the sent message to be executed before returning.

2.2.PostThreadMessage()

The PostThreadMessage method can send a message to the specified thread.

Function prototype: boolpost thread message (dword id thread, uintmsg, wparam wparam, lparam lparam);

The parameters are basically the same as PostMessage except ThreadId.

The target thread accepts the message through the GetMessage () method.

Note: When using this method, the target thread must already have its own message queue. Otherwise, an ERROR_INVALID_THREAD_ID error will be returned. can use

PeekMessage () creates a message queue for the thread.

3.CEvent object

CEvent is an object in MFC, and communication and synchronization between threads can be realized by changing the trigger state of CEvent.