Friday, November 30, 2018

The sequential option for Worker-UI interaction

This post describes the even scheduling of Worker and UI (User Interface) in an application, with optional, temporal seizure of execution time by UI on user request.

When the long-running Worker process executes, usually users want to see the up-to-date state of computation. A solution when UI copies the Worker's data, requires a lot of PC memory, hence it is not an option. A solution of putting a Worker and UI in different threads leads to the scattering of locks in Worker's code, which is a complexity overhead. For research code I want the simplicity of single-threaded application. The dilemma of UI interactivity versus single-threaded simplicity produces an interesting offspring, which to some degree poses pluses of both.

We start from sequential implementation, when a controller calls in sequence one step (some process routine) of Worker and one step (eg. render frame) of UI. The drawback is that the Worker and UI gets an even number of function calls, which leads to unresponsive UI. Next we tweak the UI's routine to grab the extra execution time in case a user generates some events with a keyboard or a mouse. These events tell the controller that the user wants some extra interactivity. Instead of switching to execute the Worker's routine, the UI continues to execute the UI loop (it renders frames and handles input events) from this moment of time 'Now', till Now plus some delay (eg. 1 second).
Each user input sets the end time of execution of UI loop by Now+1second, thus each input prolongs execution of UI cycles.
If there hasn't been an input from user for 1 second, the UI loop breaks and the Worker gets opportunity to do it's job.

Pro Worker is unaffected (locks are not required);
Pro UI does no synchronization, because at any time only the Worker or UI is executed.
Pro UI doesn't need to create a snapshot of worker's data
Con There is no actual parallel execution of a Worker. If Worker's function takes large time to execute, the UI will not be executed and thus become unresponsive.
Con User may grab execution time indefinitely by producing input events, the Worker stalls.