Message mechanism is everywhere

xiaoxiao2021-03-06  53

Multi-thread under Windows is divided into two branches. Microsoft provides AFXBEGINTHREAD to create two threads. When you create a GUI THREAD with AFXBEGINTHREAD, Windows creates an implicit window for this thread, since the window message loop mechanism must not be less. The window keeps the message from the message queue and processes the message. We can implement communication between the threads through the message. There is no implied window and message mechanism when AFXBEGINTHREAD creates Worker Thread. Communication between threads can only be implemented by functions transmitted in AFXBEGINTHREAD. Interesting is whether the parameters to be passed are stored in the stack or the AFXBEGINTHREAD can pass the parameters to the thread function specified by the user. But as a multithreaded programming, I am like letting the messaging mechanism in Worker Thread so that the communication between threads is more abundant.

Let's take a look at how to achieve this problem. Since it is a message, you should define the message ID, which message is to distinguish from which message is doing. And in the GUI THREAD Custom Message Different in Worker Thread, you should customize the message in the following method: #define my_app_message wm_app 1; now there is two questions that have two questions are sent in the main thread (do not be confused by the main thread In fact, you can send messages to another from any sub-thread) and how to receive in Worker Thread. Sending Of course, it is necessary to use PostthreadMessa, but the first thing to get the ID of the Worker Thread thread. Of course, there is no problem, we created it. Of course, everything about it is as good. The function of accepting the message in Worker Thread is the classic getMessage (); it is good.

#DEFINE MY_APP_MESSAGE WM_APP 0x0001

Handle g_hevent = NULL;

DWORD WINAPI WORKERTHREAD (LPVOID PPARAM);

/

Void cwokerthreadinmessagedlg :: CreateWorkeRTHREAD ()

{

g_hevent = creteEvent (NULL,

True,

False,

NULL);

Assert (g_hevent);

m_hworkerthread = CreateThread (NULL,

0,

Workerthread,

this,

NULL,

& m_dwwkerthread;

Assert (m_hworkerthread);

WaitforsingleObject (g_hevent, infinite);

PostthreadMessage (m_dwworkerthread, my_app_message, 0, 0);

}

DWORD WINAPI WORKERTHREAD (LPVOID PPARAM)

{

Bool bquit = false;

MSG msg;

PeekMessage (& MSG, NULL, 0, 0, PM_NOREMOVE); // Establish a message queue parameter detail to see MSDN

SetEvent (g_hevent);

While (! Bquit && GetMessage (& MSG, NULL, 0, 0)))

{

Switch (msg.message)

{

Case my_app_message:

// do the job you wanna

Break;

Case WM_Quit:

Bquit = true;

Break;

DEFAULT:

DispatchMessage (& MSG);

}

}

Return 0;

}

转载请注明原文地址:https://www.9cbs.com/read-117531.html

New Post(0)