I am applying my new found knowledge of threading everywhere and getting lots of surprises
Example:
I used threads to add numbers in an
array. And outcome was different every
time. The problem was that all of my
threads were updating the same
variable and were not synchronized.
- What are some known thread issues?
- What care should be taken while using
threads? - What are good multithreading resources.
- Please provide examples.
sidenote:
(I renamed my program thread_add.java to thread_random_number_generator.java🙂
In a multithreading environment you have to take care of synchronization so two threads doesn’t clobber the state by simultaneously performing modifications. Otherwise you can have race conditions in your code (for an example see the infamous Therac-25 accident.) You also have to schedule the threads to perform various tasks. You then have to make sure that your synchronization and scheduling doesn’t cause a deadlock where multiple threads will wait for each other indefinitely.
Synchronization
Something as simple as increasing a counter requires synchronization:
Assume this sequence of events:
counteris initialized to 0counterfrom memory to cpu (0)counterfrom memory to cpu (0)counteron cpucounterfrom cpu to memory (1)counteron cpucounterfrom cpu to memory (1)At this point the
counteris 1, but both threads did try to increase it. Access to the counter has to be synchronized by some kind of locking mechanism:Only one thread is allowed to execute the code inside the locked block. Two threads executing this code might result in this sequence of events:
myLockmyLockbut has to waitcounterfrom memory to cpu (0)counteron cpucounterfrom cpu to memory (1)myLockmyLockcounterfrom memory to cpu (1)counteron cpucounterfrom cpu to memory (2)myLockAt this point
counteris 2.Scheduling
Scheduling is another form of synchronization and you have to you use thread synchronization mechanisms like events, semaphores, message passing etc. to start and stop threads. Here is a simplified example in C#:
You will notice that access to
this.taskprobably isn’t synchronized correctly, that the worker thread isn’t able to return results back to the main thread, and that there is no way to signal the worker thread to terminate. All this can be corrected in a more elaborate example.Deadlock
A common example of deadlock is when you have two locks and you are not careful how you acquire them. At one point you acquire
lock1beforelock2:At another point you acquire
lock2beforelock1:Let’s see how this might deadlock:
flock1glock2lock1but has to waitlock2but has to waitAt this point thread A and B are waiting for each other and are deadlocked.