Home >Common Problem >What are the communication methods between threads?

What are the communication methods between threads?

不言
不言Original
2019-04-08 13:59:1151670browse

What are the communication methods between threads?

The communication methods between threads include the following:

1. Message queue is the most commonly used One, and the most flexible, allows complex and simple data structures to be transferred through custom data structures.

In Windows programming, each thread can have its own message queue (the UI thread has its own message queue and message loop by default, and the worker thread needs to manually implement the message loop), so messages can be used for inter-thread communication. Communication sendMessage, postMessage.

Define message#define WM_THREAD_SENDMSG=WM_USER 20;

Add message function declaration afx_msg int OnTSendmsg();

Add message mapping ON_MESSAGE(WM_THREAD_SENDMSG,OnTSM)

Add the implementation function of OnTSM();

Add PostMessage message Post function in the thread function

2. Use global variables

Threads in the process Memory sharing 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.

3. Use the event CEvent class to implement inter-thread communication

Event objects have two states: with signal and without signal. Threads can monitor events in the signal state so that they can be detected at the appropriate time. Perform operations on events.

1) Create an object of the CEvent class: CEvent threadStart; it is in a non-communicating state by default;

2) threadStart.SetEvent(); to put it in a communicating state;

3) Call WaitForSingleObject() to monitor the CEvent object

The above is the detailed content of What are the communication methods between threads?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn