I have twenty minutes between computer science classes for lunch. I am a CPU looking to make a turkey and cheese sandwich as fast as possible, so that I have enough time to eat.
Sequential
I could use the following procedure to make a sandwich:
- Get out bread and put two pieces in the toaster
- Wait for the toaster to finish
- Remove bread from toaster
- Get out turkey, cheese, mustard, and olive tapenade
- Spread olive tapenade one piece of bread
- Spread mustard on the other
- Remove two pieces of turkey from the package
- Put them on a slice of bread
- Remove a slice of muenster cheese from the package
- Put it on top of the turkey
- Close sandwich
This procedure is fine, and it definitely results in a tasty sandwich. But can I finish this task in less time?
Concurrent
As a CPU, I can only do one thing at a time, but the hardware I have access to can do some things without my oversight or engagement. Specifically, my toaster will count down on its own and send me an interrupt when it finishes. In my sequential procedure, I wasted time by sitting around waiting for the toaster to finish. Instead of doing nothing during that time, I could use that time to my advantage.
My new process looks like this:
Sub-task A
- Get out bread and put two pieces in the toaster
- Switch to Sub-task B
- When toaster is done, come back to Sub-task A (this one) and remove the bread from the toaster
- Spread olive tapenade one piece of bread
- Spread mustard on the other
- Finish Sub-task B, if it isn’t already finished.
- Put turkey and cheese one piece of bread
- Close sandwich
Sub-task B
- Get out turkey, cheese, mustard, and olive tapenade
- Remove two pieces of turkey from the package
- Remove a slice of muenster cheese from the package
- Put it on top of the turkey
Sub-task B takes a little bit of time, because the turkey and cheese packages are fiddly, and the turkey especially requires attention to make sure I’m not ripping the slices into pieces.
Because Sub-task A voluntarily lets me (the CPU) take a break from it to switch to my other task, I don’t waste any time sitting around. And because Sub-task B can be interrupted by the toaster finishing, I’ll be able to respond to the toaster as soon as it finishes, even if I haven’t finished with Sub-task B.
Parallel?
I’d like to be able to parallelize this task, but I think the metaphor breaks down here. I’d need a clone or twin of myself to work alongside me at the same time, and I’d need to be able to divide the task into parts that can be worked on simultaneously. I suppose my twin and I could each handle spreading one of the spreads onto one piece of bread, but other than that it seems there is very little that can be done in parallel.
Maybe since there would be two of us, we would want to make two sandwiches…
Shoutout to my Operating Systems professor :)