Proper Multithreading: Let’s Remind Ourselves What it is
That sounds ideal, but what does it take to have real multithreading with appropriate locks and to secure your program so it can run smoothly without you worrying if you will ever get a deadlock or a race condition?
Just some locks, semaphores, and a lot of time to think it through.
I mean, how else? It would be crazy to ask for it do multithreading security itself. We can begin with how you should lock your program and prevent deadlocks.
What is proper multithreading and how to do it?
There is a certain flow of the program that has to be reached in order for it to work without deadlocks and data loss. Deadlocks or race conditions can occur while you are accessing shared resources from multiple threads at the same time. When you run a program with multithreading it is very hard to debug what happens when exactly and which thread has priority over other threads to access the shared resource. Here is where locks come into play and we use them to prevent those same deadlocks.
Another important thing to mention is context switching, which is a procedure that a computer’s CPU (central processing unit) follows to change from one task (or process) to another while ensuring that the tasks do not conflict. Effective context switching is critical if a computer is to provide user-friendly multitasking.
Let’s talk about locks in more detail.
There are a couple of different locks:
Mutexes and Condition Variables
Stands for mutual exclusion and protect shared resources that are being used by multiple threads. Shared resources need to be protected in order to make sure data that is being written/read is properly manipulated.
To put it in simpler words, there can be a global variable and it can be accessed by multiple threads. You are locking it because one thread can write and others can read from it, but that needs to happen in a certain order.
And this is how mutexes work simplifiedExampleMutex example in C
There are many functions related to the mutex controls and you can look through all of them over here
for C++. Most of the functions for the locks are similar in all languages.
A condition variable allows any number of threads to wait for another thread to signal a condition and they can start working.
It uses a unique_lock (over a mutex) to lock the thread when one of its wait functions is called. The thread remains blocked until woken up by another thread that calls a notification function on the same condition_variable object.
It works along the mutex and you can look at all the features here
That was a brief overview and a reminder for locking your program with mutexes and condition variables in order to achieve perfect multithreading.
Previously published at https://towardsdatascience.com/proper-multithreading-have-perfect-multithreading-in-your-program-4cbbf8270af3
Subscribe to get your daily round-up of top tech stories!