Post a Thread Message and also handle it in the simplest way






1.73/5 (7 votes)
Jul 31, 2004
2 min read

56501

3072
The message posted to a thread can be easily handled by PeekMessage loop in a similar way as it is done in a window's message loop.
Download all the Zip files, recommended.
ThreadMSG
dialog looks some what like this:
The Thread starting with AfxBeginThread
dialog looks like this:
Description
This little software does noting but start a Thread, and the title bar blinks to show that it is running. Although a number of threads can be started, in this program that feature has not been stressed. It only handles MSG messages that are send to it or posted to it. One way of doing it can be deriving a class from CWinThread
using its normal message maps.
class Thread:public CWinThread {DECLARE_DYNCREATE(Thread) public:.... afx_msg void OnRun(WPARAM wParam,LPARAM lParam); DECLARE_MESSAGE_MAP() }; IMPLEMENT_DYNCREATE(PlaySound1, CWinThread) BEGIN_MESSAGE_MAP(PlaySound1, CWinThread) ON_THREAD_MESSAGE(WM_ON_RUN,OnRun) END_MESSAGE_MAP() void OnRun(WPARAM wp,LPARAM lp) { ..... ..... } ////To start a thread use the following lines anywhere ////Preferably use OnInitDialog()for general purpose ////first declare an instance of the class Thread with ////the visiblity mode of your preference BOOL CThreadMSGDlg::OnInitDialog() {Thread *pThread; pThread=new Thread; pThread->CreateThread(); play->PostThreadMessage(WM_ON_RUN,0,0); ... ... return TRUE; } /*///#///Note: Do not use the overloaded Run function of CWinThread it wont let you use ON_THREAD_MESSAGE */
But here, I am using a trick. No need to derive a class from CWinThread
. But first download the source code, and then you will find the following methods being implemented there:
- First method: The Thread is being started using API function
CreateThread(....)
. This also takes a parameter as a pointer to itsthreadID
and returns the thread ID. This ID is referred to while posting messages byPostThreadMessage(...)
in a very similar way._beginthread(....)
function can be used which also gives us thethreadID
. - Second method: The Thread can also be started using (Preferred in MFC based programs)
AfxBeginThread(ThreadProc,lpvoidParam)
. What it returns is the pointer to aCWinThread
object. And there is a public member variable in it:m_nThreadID
. So, it also gets initialized by this function. This can be used to post messages to it.
Use PeekMessage
to see if there is any message, because this function returns if there is no message, while GetMessage
waits infinitely until there is no message. This can lead to blocking of the thread. So take care.
If you have any problems or any queries, feel free to write to me at mailto:sammyitm@hotmail.com?subject=query about project.