CSUMB

CSUMB 334 - Week 6

Author

Date Published

CSUMB logo 2

Multi Threading!


So last week we learned about threads, this week we learned about multi-threading. The gist of what we learned is that multi-threading is a lot like managing single threads except you have the existential threat of deadlocks and race conditions always waiting for you to slip up. We covered how we could use semaphores to manage our threads and do our best to prevent such scenarios. However, my big takeaway was just try to use the posix multi-threading API to manage it because 9 times out of 10 I will mess it up and debugging these situations looks painful.

However, with modern machines frequently having dozens of threads, becoming adept with multi-threading in a low level language like C can greatly improve the performance of what otherwise would be a slow single-threaded process. At an old job I was tasked with parsing large CSVs and I only knew how to write code in Node.js. I can only imagine how fast I could have gotten that parser to run if I could have split the CSV file into a chunk for each thread to process!


On a technical level; deadlocks can occur due to the following situations:

1. circular waiting

2. hold and wait

3. no preemption

4. Mutual exclusion

the posix API prevents this by simply polling a lock to see if its available.

Race conditions can occur if a process is not waited appropriately and executes something in parallel when it should by synchronous. This also applies when trying to do stuff across multiple processes not just between multiple threads in the same process.

Comments

Join the conversation! Login to reply to comments