Can someone post an example of how to kill a thread created by button.pressed() or button.released() from inside of main() instead of from inside of the thread itself? One thing I’m not sure of is whether it’s considered a thread or a task or if that even matters. I know they’re functionally the same, but in creating it which it is may matter.
It’s a bit unfortunate things are this way. Consider the brain-screen button code you wrote. I have some students working starting with that. Once they’ve made their selection they want to move on. They have a button to exit the while loop to move on to the next bit, but the event handlers keep looking for presses even if they are trying to do something different with the screen now. Fortunately, they’re recording the information separately when they exit the loop, so messing around with the screen afterward is just annoying but won’t mess up their selections.
I guess the approach will be different, then: when you’re trying to kill them you can set global Booleans to mark them as needing to be killed, and the threads can kill themselves if their event shows up and their marked to be killed. Are the event handlers “threads” or “tasks”? I ask because that determines .stop v. .interrupt as the method.
As part of the event register function, the OS might kick off a thread that monitors the memory locations that hold the LCD screen outputs, but the function you’re telling that process to call has no knowledge of it, it’s simply a function being called to do something.
Others with more knowledge of the architecture might be more helpful there.
I would think that you could manage the behavior of the callbacks with a global state variable. When you exit the menu while loop, you set the variable to a value that prevents the registered callback function from doing anything when it’s called.
For example, @jpearman’s code might look like this instead:
//global state variable
int state = 0;
void userTouchCallbackPressed() {
if (state == 0) {
int index;
int xpos = Brain.Screen.xPosition();
int ypos = Brain.Screen.yPosition();
if( (index = findButton( xpos, ypos )) >= 0 ) {
displayButtonControls( index, true );
}
}
else if (state == 1) {
// something else
}
else if (state == 2) {
// something else
}
}
If the state is anything other than 0, 1, or 2, the function does nothing.
Might be a great springboard for an introduction to state machines with your students, too.
“Indeed, the ratio of time spent reading versus writing is well over 10 to 1. We are constantly reading old code as part of the effort to write new code. Therefore, making it easy to read makes it easier to write.”
Sounds like a good fix. If you can’t kill it, paralyze it.
This does leave the ugly bit of stray threads existing and using up space. But there aren’t likely to be so many of these paralyzed threads existing so that shouldn’t really be a problem.