Hem
Hem

Reputation: 97

Worker thread doesn't have message loop (MFC, windows). Can we make it to receive messages?

Mfc provides both worker and UI thread. UI thread is enabled with message receiving capabilities (send, post). Could it be possible to let worker thread too receive messages.

Upvotes: 1

Views: 4034

Answers (3)

bert-jan
bert-jan

Reputation: 968

Call CWinThread::PumpMessage() repeatedly until it returns a WM_QUIT message.

Upvotes: 2

Ajay
Ajay

Reputation: 18451

It seems you need a thread, that can handle multiple messages from another threads. Another threads would add-a-message to the message-queue of this thread. Well, in that case you may use PeekMessage to startup a loop, which would eventually create a hidden window, and then use GetMessage to get the messages. The other threads would use PostThreadMessage with the thread ID (the one having Peek/GetMessage), and the message-code, LPARAM, WPARAM.

It would be like (not syntactically correct):

TheProcessor()
{
    MSG msg;
    PeekMessage(&msg,...);

    while(GetMessage(&msg...)
    {    /* switch case here */ }
}

The threads would call PostThreadMessage - See MSDN for more info. When you need to send more data than LPARAM/WPARAM can hold, you eventually need to allocate them on heap, and then delete AFTER processing the message in your custom message-loop. This would be cumbersome and buggy.

But... I would suggest you to have your own class, on top of std::queue/deque or other DS, where you can add AddMessage/PushMessage, and PopMessage (or whatever names you like). You need to use SetEvent, WaitForSingleObject to trigger the new message in loop (See one of the implementation here. You may make it generic for one data-type, or make it template class - that would support any data-type (your underlying DS (queue) would utilize the same data-type). You also need not to worry about heaps and deletions. This is less error prone. You may however, have to handle MT issues.

Using Windows events involves kernel mode transition (since events are named/kernel objects), and you may like to use Conditional Variables which are user objects.Or you may straightaway use unbounded_buffer class from Concurrency Runtime Library available in VC10. See this article (jump to unbounded_buffer).

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 613572

Yes you can create a message queue on a worker thread. You will need to run a message pump on that thread.

Upvotes: 0

Related Questions