Three ways to communicate between "turn" VC threads

Source: Internet
Author: User
Tags response code

Original URL: http://my.oschina.net/laopiao/blog/94728

1. Using Global variables (form not applicable)
There are many ways to implement inter-thread communication, which is mainly implemented by global variables, custom messages and event objects. The use of global variables is most concise. This method takes a global variable as a thread-monitored object and implements child-threading control by changing the value of the variable on the main thread.
Because the global variable here needs to change its value outside the thread that uses it, this variable needs to be described by the volatile keyword. The method of using global variables for thread communication is very simple, and the sample code given below provides a basic understanding of it.

Global variables for thread communication
volatile bool G_bdo = false;
......
Thread-handling functions
UINT ThreadProc5 (LPVOID pparam)
{
Determines the running of a thread based on the value of the global variable G_bdo
while (G_BDO)
{
Sleep (2000);
AfxMessageBox ("Thread is running!");
}

AfxMessageBox ("thread termination");
return 0;
}
......
void Csample06view::onglobalstart ()
{
Notify thread execution with global variables
G_bdo = true;

Start thread
AfxBeginThread (THREADPROC5, NULL);
}
void Csample06view::onglobalend ()
{
Notify thread end with global variables
G_bdo = false;
}

2. Using custom messages (available for forms)
The application of global variables in thread communication is more used in the main thread to control the child threads, while the feedback from the child thread to the main thread is used in the way of custom messages. The use of custom messages here is very similar to using a normal custom message, except that the message is sent in a child-threaded function. The body of the method is a custom message, and you should first define a custom message and add a response code to the message.

Custom messages
#define WM_USER_MSG Wm_user + 101
......
The message response function is defined in the header file:
{{afx_msg (Csample06view)
}}afx_msg
afx_msg void Onusermsg (WPARAM WPARAM, LPARAM LPARAM);
Declare_message_map ()
......
Message map
Begin_message_map (Csample06view, CView)
{{Afx_msg_map (Csample06view)
}}afx_msg_map
On_message (wm_user_msg, onusermsg)
End_message_map ()
......
Message response function
void Csample06view::onusermsg (WPARAM WPARAM, LPARAM LPARAM)
{
Report message
AfxMessageBox ("Thread has exited!");
}

Thereafter, the child-threading function calls the PostMessage () or SendMessage () message-passing function to send the message to the main thread, where it needs to be sent to the main thread. Because the message send function is called in the thread, it is necessary to indicate that the handle to the window is accepted, which can be passed into the threading function through the thread parameters.

UINT ThreadProc6 (LPVOID pparam)
{
One second delay
Sleep (1000);

Send a custom message to the main thread
::P ostmessage (HWND) pparam, wm_user_msg, 0, 0);
return 0;
}
......
void Csample06view::onusemessage ()
{
Get Window Handle
HWND hwnd = GetSafeHwnd ();

Start thread
AfxBeginThread (THREADPROC6, hWnd);
}

3. Using Event kernel objects (quite handy)
The use of event kernel objects to communicate with threads is more complex, primarily through the monitoring of event objects to achieve inter-thread communication. The event object is created by the CreateEvent () function, which has two existing states: Set and reset, which are generated by SetEvent () and ResetEvent () respectively. The placement of the event will continue through a notification wait function such as WaitForSingleObject () or waitformultipleobjects ().

Event handle
HANDLE hevent = NULL;

UINT ThreadProc7 (LPVOID pparam)
{
while (true)
{
Wait for event to occur
DWORD Dwret = WaitForSingleObject (hevent, 0);
Exit the thread if the event is set, or continue execution
if (Dwret = = wait_object_0)
Break
Else
{
Sleep (2000);
AfxMessageBox ("Thread is running!");
}
}

AfxMessageBox ("Thread terminates run!");
return 0;
}
......
void Csample06view::oneventstart ()
{
Create Event
hevent = CreateEvent (null, FALSE, FALSE, NULL);

Start thread
AfxBeginThread (ThreadProc7, NULL);
}

void Csample06view::oneventend ()
{
Event-Placement
SetEvent (hevent);
}

The above code shows the role of event objects in thread communication. Creating a line Chengqian first creates an event object hevent, where the CreateEvent () function takes four parameters to indicate that the handle cannot be inherited, that the event is reset by the system automatically after it is set, that the initial state of the event object is the reset state, and that the event name is not specified. The hevent is monitored using WaitForSingleObject () in the child threads that are created. The function prototypes for WaitForSingleObject () are:

                 DWORD WaitForSingleObject (
                                HANDLE Hhandle,                              //Handle of waiting object
                                 DWORD dwmilliseconds           //Over time interval
                 );

The function will be returned when the Hhandle object is signaled or when the wait time exceeds the timeout interval set by dwmilliseconds. The return value can be wait_abandoned, wait_object_0, and Wait_timeout, respectively, indicating that the waiting mutex (mutex) object is not freed, the object signal to wait is set, and the time-out is exceeded. The reason for the return of the WaitForSingleObject () function can be distinguished by judging the return value. In this case, only the return value of the WAIT_OBJECT_0 is concerned, and when the hevent is placed through SetEvent (), the WaitForSingleObject () is returned immediately and the thread is terminated by jumping out of the loop.

Note: The return value of the message handler function you added must be lresult, otherwise the "On_message conversion type is invalid" message appears!!!

Three ways to communicate between "turn" VC threads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.