I have a two buttons in a form: START and STOP. The START button starts a function with a loop inside (this loop could take a lot of time to be concluded) and after that calls an other function for data post-processing. I want to be able of stop and exit the loop pressing the STOP button. I have already a boolean to check if STOP was pressed, but the problem is that the system doesn't recognize button events while the loop is running. I have to start a thread for the loop function? If so, the post-processing function will be called only at the end of the loop (if STOP was not pressed)? Thank you in advance.
Thank you, IcerLion. At this moment I have started a thread to run my loop function. I'm expecting that the STOP button click was percieved by the application, my 'should_stop' boolean was updated to 'true' and I could 'break' my loop and exit that function. Unfortunatly, it is no so. Despite I have a thread running the loop function the system seems to doesn't handle the click button event... What could be missing in my approach? Thanks. Joao
EDIT: The principle applies to UNIX/Linux, but the mentioned functions are Windows-only.
To signal a thread you better use an event.
When the start button is depressed, use CreateEvent() to create a new event. Pass this event as part of the data that you pass to the new thread. I recommend that you declare a suitable struct for this.
Inside the worker thread, use WaitForSingleObject() with a timeout of zero. If the function returns WAIT_OBJECT_0, the thread has been signaled to stop.
On depress of the Stop button, use SetEvent() to signal de stop event.
Finally, if you must synchronize the user interface, one Stop use WaitForSingleObject() to wait for the worker thread to finish, then update the UI as needed.