Thursday, February 2, 2017

How to explain Threads

People new to programming might have hard time  understanding what are "threads". How are they different from "programs"?  There's a simple metaphor you can use to explain  the concept of "threads":

Your  program is like a labyrinth.  You can't walk "through it", you must follow the paths that exist. There are many branches in those paths you can take. You can go forwards and you can reverse your direction to return to an earlier point. You can pick things up to carry with you while inside the labyrinth, maybe just some information, maybe take photographs.

The program has run its course when you return back to the entry-point and exit. You still have the things you picked along the route, the photographs you took etc. Those are your output. What you took with you into the labyrinth was your input, say a map which guided your choice of turns at the branch-points.

The above  is single-threading. You moving inside the labyrinth is like the program-counter in your program's execution environment pointing to different locations in the program being "run". (Yes you can run in a labyrinth too, you must if a Minotaur is chasing).

Now leash multiple visitors into the same labyrinth, more or less at the same time, concurrently . They will choose their own paths according to their own maps. They might communicate with each other by leaving notes on the walls for others to read. Some visitors might overwrite notes written by others, probably not a very good practice but certainly possible. This is multi-threading: Multiple visitors in the labyrinth at the same time. Each visitor walking inside the labyrinth is one thread.

Why are  they called "threads"?  I can think of one reason. In the Minotaur-myth Theseus entered the labyrinth with a  ball of thread.  He tied the start of the thread to the entry point of the labyrinth. Then he unwound the thread as he moved deep into the Labyrinth. After he found the Minotaur and killed it he needed a way to find his way back out. He simply followed the unwound thread.

Copyright © 2017 Panu Viljamaa. All rights reserved