Threads
Using threads in applications is often a must. Without threads applications would often stop responding to user input and seem to “hang” which users do not like. Also many modern computers have more than one CPU and using threads enable one application to take advantage of multiple CPUs.
There are also a HUGE number of problems associated with threads, and very often when application crash it is because of bugs related to threads.
- Threads access resources that belong to and only work in other threads.
- Do not assume that resources are designed to be used from a thread different from the thread where it was allocated.
- Do not use a resource created in one thread in another thread unless it is designed to be used that way.
- Using a mutex or other locking mechanism does NOT make it safe to use a resource in multiple threads.
- Multiple threads access the same objects at the same time.
- Most people know they must use a locking mechanism to prevent simultaneous access to resources shared between multiple threads, but actually doing it is another thing.
- Just because you use a mutex to protect a resource does not mean that others do. Unless a resource is owned by your code, and is never accessed directly by others code, assume that it can NOT be protected by a locking mechanism.
- The best way to make a resource thread safe is to hide it inside an object and make sure that the object enforces the locking mechanism. This leads to another problem, which is addressed below. Such an object must never expose the protected resource to the outside, it is does, somebody will start accessing the resource circumventing the locking mechanism.
- In most cases threads communicate with each other by passing references to resources. When they do, it is vital to control when a resource sent from one thread is handed over to the other thread. A good thread communication system can help eliminate bugs.
- Threads deadlock because they attempt to lock multiple resources at the same time.
- If one thread lock a mutex A and the attempt to lock mutex B locked by another thread it must wait. If the thread that locked mutex B try to lock mutex A, both threads will wait forever.
- To avoid this, do not lock a mutex and then start doing a lot of things, because some of these things may lock other mutexes you have forgotten about, and that can lead to deadlocks.