Multithreading is not as hard as it sounds
I’ve been finally forced to really learn about multithreading, and I’ve got some basic concepts down. I sifted through a lot of articles and tutorials and I think this one is the best. Here’s the scoop:
Threads do the actual execution in a process, and they can all access the same region of memory. If you’ve got multiple threads, you don’t want one to try to read from a block of memory while another thread is in the middle of writing to it, so you can use something called a mutex (meaning “mutual exclusion”) object to control this. A mutex gives your program a way of saying “only this thread is allowed to work until I say so,” so you can read or write the entire block of memory safely. It’s as simple as that! Here’s a Windows C++ example and a pseudocode example:
var theData var myMutex = CreateMutex() waitForMutex(myMutex) writeTheData(theData) releaseMutex(myMutex)
Seriously, that’s really all there is to it. At first I thought you had to specify which thread you want to do the work but I was thinking of it backwards; mutexes say “whichever thread is going now, don’t stop it until I say so.” Bing!