Multi-threaded object pointer must be used with caution

xiaoxiao2021-03-06  83

In multi-threaded environments, the auxiliary thread and main thread communication are usually required, and the general auxiliary thread is the user thread, start with CreateThread, or AFXBEGINTHREAD. (Recommended latter)

AFXBEGINTHREAD (Proc, NULL);

Where PROC is a function name, it is defined as:

UINT Proc (LPVOID LP) {

HWnd hwnd1 = (hnwd) lp; :: SendMessage (HWND1, WM_USER 12, 0) // Take a message mechanism, WM_USER 12 is a message value defined ((cmfcc2dlg *) AFXGETMAINWND ()) -> OnBnclicKedButton2 () ; // Take the object pointer directly to access a function

Return 1;}

There are two ways to communicate, one is to use global variables, the second is to take a message mechanism, a custom message in the auxiliary thread, inform the interface thread to respond!

For a while, I don't understand why I want to use the message mechanism notification, get the object pointer of the main thread through the AFXGetMainWnd (), and then call the response function through the pointer, isn't it very convenient?

It is self-satisfied with your own discovery, and thinks that it can save the next list of messages. Many, find that your project has a big bug, run to a pointer judgment, the program report memory read and write conflicts, the breakpoint is

If (chakandlg! = null) there, theoretically, this did not perform anything, why always report the wrong report!

I really can't find the reason, then view the functions belonging to this statement, find out what weird, find it is a supply auxiliary thread, directly passing the object pointer, is it in this?

I always feel unlikely, but only this is possible! Then I re-establish a message response function, customize a message, by sending a custom message in the auxiliary thread -! ! ! ! ! ! ! !

No more rewards, read errors!

I am dizzy, it is really here!

I have thought about it for a long time, I feel that the only explanation is the interface thread to use this variable, then the secondary thread passes the object pointer, and this variable is used, and the two conflicts? ? ? ? Don't read the variables in another thread in a thread, even if both are reading? ?

It is also explained, but usually, through the object norms call function, still there is no problem, but the best program is still using the message mechanism, which will not mess up the steps of the main thread to prevent accidents!

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

New Post(0)