Re: An multithread question.
<cwyang@cis.nctu.edu.tw> wrote in message
news:1156768337.914293.127920@h48g2000cwc.googlegroups.com...
Hi there,
I've now encountered a hard problem.
As we know, in a dialog-based program, when we press a
button, the windows wait for the corresponding procedures
to be executed. During executing those procedures, the other
windows message won't be taken care.
I've ever used a library, it provides two functions.
One is Go(), and the other is Stop().
I created two corresponding buttons ButtonGO, and ButtonStop
to do Go() and Stop().
I don't have to use AfxCreateThread in OnBottonGO. When I press
ButtonGo, the ButtonStop button is still pressable!
When I press ButtonStop, the OnButtonGo() function shall return.
How this can be done?
Any suggestion will be appreciated.
This can be done if the button handler (or the Go() function) pumps messages
while it is executing. Code like this:
void Go()
{
while (GoFunctionIsNotYetDone)
{
// do part of a lengthy procedure
// ..
// every once in a while, pump messages
MSG msg;
while( ::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )
{
::TranslateMessage( &msg );
::DispatchMessage( &msg );
}
}
}
This code will periodically pump messages, including mouse messages and
notifications like BN_CLICKED, and thus your buttons will remain press-able.
Code like this originated with early Windows OS's like Win 3.1, in which
applications could not be multi-threaded. The classic example of this code
is found in Petzold's example for the "Cancel Print" dialogs that were
displayed while processing a document for printing (which was a lengthy
process).
Use of code like this now is not generally recommended, since current
Windows OS's are all pre-emptively multi-threaded. Unless you have a real
need not to create a thread, it's generally recommended to create the thread
instead of using "pump messages" code like that above.
Mike