When a program requests some information from an external source (say, from a web server) we usually want it to give up after some amount of time instead hanging indefinitely awaiting a response that may never arrive.
asum function in
Data.Foldable chooses the first feasible action among a list of possibilities.
resultis initialized to
Nothing. When our imaginary task (doing nothing for two seconds) completes, it assigns the value
Just "Task A: ..."to the
timeoutis initialized to
False. We fork another thread which waits for one second and then changes it to
The race is now on; what we care about now is which of these two variables changes first.
- Read a
The program pauses here until either of these two actions is able to run.
Printing the resulting string will tell us which of the two possibilities actually ran.
Since Task A takes two seconds and the timeout is one second, the timeout will happen first.
Now we’ll try the same thing again, but with Task B completing in only half a second (500,000 microseconds, written as
500_000 with the comma replaced by an underscore).
The timeout is one second again.
So this time, the reading of the completed task’s result will be the action that becomes runnable first.