You can use the PostThreadMessage function to communicate between threads:
PostThreadMessage 's prototype is like this.
BOOL PostThreadMessage (DWORD idthread,
UINT MSG,
WPARAM WPARAM,
LPARAM LPARAM
);
PostThreadMessageCan be used for asynchronous communication between threads, because it does not wait for the caller to return,
This may be the simplest way to thread communication.
But be aware of the following issues
1. PostThreadMessage sometimes fails, reporting 1444 errors (Invalid thread identifier.)
In fact, this is not necessarily the reason why the thread does not exist, and it is possible that the thread does not exist for Message Queuing.
In fact, not every thread has a message queue, so how does the thread have it?
The answer is to call at least one message-related function, such as getmessage,peekmessage.
2. If the post is dynamically allocated to another thread, pay attention to the correct memory release.
3.PostThreadMessage can not post wm_copydate such as synchronization messages, or will error
4. It is best not to use PostThreadMessage Post message to a window, using PostMessage instead.
Here is an example of a comparison thorough I have written, for reference only.
#include <windows.h>
#include <cstdio>
#include <process.h>
#define MY_MSG wm_user+100
const int max_info_size = 20;
HANDLE hstartevent; Thread Start Event
Thread function
unsigned __stdcall fun (void *param)
{
printf ("Thread fun start \ n");
MSG msg;
PeekMessage (&msg, NULL, Wm_user, Wm_user, Pm_noremove);
if (! SetEvent (hstartevent))//Set Thread start Event
{
printf ("Set Start Event failed,errno:%d\n",:: GetLastError ());
return 1;
}
while (true)
{
if (GetMessage (&msg,0,0,0))//Get MSG from message queue
{
Switch (msg.message)
{
Case MY_MSG:
char * pInfo = (char *) Msg.wparam;
printf ("Recv%s\n", pInfo);
Delete[] PInfo;
Break
}
}
};
return 0;
}
int main ()
{
HANDLE Hthread;
unsigned nthreadid;
Hstartevent =:: CreateEvent (0,false,false,0); Create Thread Start Event
if (hstartevent = = 0)
{
printf ("Create Start Event failed,errno:%d\n",:: GetLastError ());
return 1;
}
Start thread
Hthread = (HANDLE) _beginthreadex (null, 0, &fun, NULL, 0, &nthreadid);
if (hthread = = 0)
{
printf ("Start Thread failed,errno:%d\n",:: GetLastError ());
CloseHandle (hstartevent);
return 1;
}
Wait thread start event to avoid postthreadmessage return errno:1444
:: WaitForSingleObject (Hstartevent,infinite);
CloseHandle (hstartevent);
int count = 0;
while (true)
{
char* pInfo = new Char[max_info_size]; Create dynamic MSG
sprintf (PInfo, "msg_%d", ++count);
if (! PostThreadMessage (Nthreadid,my_msg, (WPARAM) pinfo,0))//Post thread MSG
{
printf ("Post Message failed,errno:%d\n",:: GetLastError ());
Delete[] PInfo;
}
:: Sleep (1000);
}
CloseHandle (Hthread);
return 0;
}