MSol
MSol

Reputation: 11

buttons on wxWidgets

I am programming a GUI with wxWidgets. I got a button to open a serial port and receive data. In there is a while(1) loop to constantly receive the data.

Now I want to do a "Disconnect" button to stop receiving.

Is there an event handler or a callback function to interrupt the while and jump out of the loop from the first button, when I press another button?

Upvotes: 1

Views: 444

Answers (2)

If you have a while(1) loop in the callback function for "button pressed", you will hang the UI. Callback functions must return quickly.

The quickest solution is to put the while(1) loop into a worker thread. That way your GUI won't hang.

The next problem is how to stop the loop. That's quite easy. Change the loop into:

while (keep_going.load()) {
    ....

where keep_going is of type std::atomic_bool. Then your "stop" button just calls keep_going.store(false).

Upvotes: 0

Ripi2
Ripi2

Reputation: 7198

A wxButton sends a message when it is clicked. Create a handler for this message where you do your "interrruption".

Now, a loop can be only exited from its inner guts. I mean, inside the loop you should check a flag, and depending on the value of this flag continue or exit.

My advice is that you create a worker thread. When the button "connect" is clicked then you create the thread that receives data.
This thread checks an extern flag and finishes depending on the value of the flag.

The "disconnect" button click-handler just sets that extern flag to a value that makes the thread exits when it checks that flag.

Take a look at the thread sample provided with wxWidgets sources.

Upvotes: 3

Related Questions