Categories
Linux Tutorial Series

Linux Tutorial Series – 105 – A trip back down the OS lane – threads

Here is the video version, if you prefer it:

Today, let’s go back down the good ol’ OS lane and talk about something called threads. A side note: I tried to fit in “memory lane”, but I couldn’t; it wouldn’t fit the content.

A thread is a sequence of commands that can be executed. A process always has at least one thread, but it can have multiple threads.

“Why have multiple threads?”, you may ask. A fair question. If you divide up the task into multiple threads (and assuming you have multiple processor cores), each thread can execute in its own core and the job can be done faster. An example: Say you were multiplying two matrices – each was of dimensions 20 000 x 20 000. You could do it in one thread, or maybe you could create 4 threads, each dealing with a particular part of the matrix. Or you could have 8 threads, or 80 threads – doesn’t matter. The point is, the more threads you have, the faster the program will execute, if you have the appropriate processor (one that has multiple cores) or multiple processors in your system (as in servers).

A thing I want to mention: Even if you have one processor core, you may have many apps open and they seem to be working flawlessly. In that case, what is actually happening is that you have an illusion of multitasking – your processor is just switching between programs very fast. You don’t even notice that switch, but again, it is an illusion of parallel execution. (Ward, 2014)⁠

A thing I also want to mention: Dealing with threads is hard. Like, real hard. An example: Say you have two threads running concurrently (at the same time). Let’s call them thread A and thread B. Say both of them want to write in the same memory location. What can happen? Well, thread A can write its result first, then thread B can write its result and you have the result of the thread B. The reverse is also possible – thread B can write its result and that result can get overridden by thread A. Or, thread A can be writing its result, thread B starts writing its result in the middle of thread A writing its result… It is a mess. And again, to repeat, it is hard to manage threads. There are mechanisms to deal with thread management, but just know that dealing with threads is hard.

Hope you learned something useful!

References

Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Page 5-6

NewsletterUpdates on interesting things I am doing

Subscribe to my newsletter to keep abreast of the interesting things I'm doing. I will send you the newsletter only when there is something interesting. This means 0% spam, 100% interesting content.

Leave a Reply

Your email address will not be published. Required fields are marked *