I couldn't find a better topic but here it is; 1) When user clicks a button, code starts t work,2) When another button is clicked, it would stop doing whatever it does and start to run the second button's code,3) Or with not user interaction, an electrical power down detected from a connected device, so our software would cancel the current event and start doing the power down procedure.How is this design mostly applied to code? I mean stop what you are doing part? If you would say events, event handlers etc. how do you bind a condition to the event? and how do you tell the program without using laddered if's to end it's process?method1();if (powerdown) return;method2(); if (powerdown) return;etc.
design for interruptable operations
design patterns;control structures;event sourcing;interruptions
One approach that will yield stable code is to use a state machine. Then it is best to differentiate:eventsprocesses/tasks in progressstate of your program (i.e. idle, running a task, shutting down) Here is a very simple, informal example (in pseudo-code):enum States = {idle, runningTask, poweringDown, stopped}enum events = {button1, button2, powerDown, stop}currentState = States.idle;currentTask = nil;// simple state engine. make it a critical section for thread safetysynchronized processEvent(event) {  switch(currentState) {    case States.runningTask:       currentTask.stop();       currentState = nil;       currentTask = nil;       break;    default:    }  switch(event) {    case events.button1:          if(currentState != States.idle) break;         currentTask = task1.start();         currentState = States.runningTask;         break;    case events.button2:         if(currentState != States.idle) break;         currentTask = task2.start();         currentState = States.runningTask;         break;    case events.powerDown:         if(currentState != States.idle) break;         currentTask = powerdown.start();         currentState = States.poweringDown;         break;    case events.stop:         if(!powerdown.finished())           exception(stop received before power down);         currentTask = nil;         currentState = stopped;         break;    default:          exception(event unknown);  }}// onButton1Pressed will call processEvent(events.button1)// onButton2Pressed will call processEvent(events.button2)// task1, task2, powerdown are assumed to implement some form of thread protocol,//i.e. start() returns an object referencing the new thread, stop() kills the thread  