I have a task system that is controlled by a kernel. This is a simplified version of the spawn logic:
var task = new taskCtor();
taskState.state = INIT; // taskState is private to kernel
task.init();
taskState.state = RUNNING;
task.run();
taskSpawned.emit(task.id); // this is a signal that notifies system a task has been spawned
return task.id;
The problem is killing tasks. Any task in the RUNNING state can be killed by a call to kernel.kill():
kernel.kill(tid);
The problem is what happens if a spawned task is killed by itself while its run() method is executing? We'd still emit the taskSpawned signal, even though the reference to the task is no longer valid. Potential solutions:
- check for dead task after run() call and don't emit signal if already dead
- introduce a new state and don't allow task to be killed while its run() method is running
- call run() asynchronously so we're guaranteed that the task is still alive when the signal is emitted
I don't like 1 because it's just incorrect. The task was spawned so the signal should fire.
I don't really like 3 because it introduces further complexity because the new task that's returned from the kernel will not be in the RUNNING state so it won't be possible to e.g. send messages to the task until the next tick of the event loop.