DEV Community

Damgt Studios
Damgt Studios

Posted on

Syncing threads

The Problem

Multithreading is an incredibly useful thing when making complex, computation heavy programs. This is because it allows the program to run multiple functions at once. This is all well and dandy until you run two threads that require data from each other, or worse yet, they require the exact same data from one source. For the latter example, imagine 2 toddlers wanting to play with the same toy, so they do what toddlers do best and try to snatch it from each other and break the toy in half (though there’s less crying and screaming when the threads do it). The same thing happens with the data being accessed by the two threads since they’re trying to modify it simultaneously.

The solution

Since I posed two problems with multithreading, I feel like I’m required to give two answers. I don’t usually do this, but I’ll make an exception just this once. The first problem (two threads requiring data from each other) The best solution would be a future and promise. I know these sound like vague concepts that’ll teach you more about yourself, but I assure they’re actual programming terms. A future is a data type that blocks a thread until it receives data from a promise. In essence, a future is like a friend that’s stopping the group from going anywhere because they’re assuring us that the latecomer (the promise) is definitely on their way, and this friend is one hundred percent certain that the missing person will show up, so they stop everything until they eventually arrive (or it’ll stop everything forever because you forgot to set the promise).

The second problem (two threads trying to access the same data) can be solved using a mutex lock. A mutex lock is a way for a thread to call dibs on some data. For example, if thread 1 wanted to access an integer so that it can add the number 2 to it, but thread 2 also wanted to access that same integer so that it may subtract 2 from it. Ignoring the counterintuitive nature of this program, the two threads now have to race each other to get that integer, and whoever gets to it first will use the mutex to lock that piece of data, which forces the other thread to patiently wait it’s turn while the faster thread does whatever it needs to do.

Ahmed Fayez

Top comments (0)