Sunday, October 20, 2013

Multithreaded programming in layman's terms

Multithreading is a software concept that allows several programs run in parallel. While getting my head around it and talking to lots of folks about it I conveyed that we can compare multithreading with the real world.
Let's map concepts from the world of threading to the real world concepts.
OS is an enterprise. There're many different departments working at the same time. They can interact to each other in some way but it's not necessary.
Processes are rooms for the employees. Effectively rooms do not do anything. They are just compartments for the employees to work in.
Threads are employees. They are the ones doing any job we have whether it's designing a new marketing strategy or wiping out the streets.
Every enterprise can create rooms when it has a project to work on and assign employees to it. Usually you start with one thread per process and create more as you need.
Now, synchronization is a concept that can take a while to grasp. It is a way to allow different threads to interact with a shared resource.

Let's assume we have a single bathroom. If we were to allow multiple folks inside it would be hard to cope with the aftermath. So there can be only one person at a time. And that's what we achieve with synchronization. The simplest synchronization mechanism is mutual exclusion. Effectively it's closing the door from the inside once you're in. And nobody but you can unlock it.
Now there's another synchronization concept also described by Dijkstra called semaphore. It's a mutex with a counter assigned to it. Let's assume we have a bathroom with four standalone rooms. Once all the rooms are occupied the entry automatically gets locked out. Once there's a vacancy the door gets open again.
So far it's the simplest metaphor I came up wth. But it works while explaining it to newbies.