Optimizing C++/Writing efficient code/Thread usage
Contents |
Worker thread [edit]
Every time in an interactive application you must perform an operation that can take more than few seconds, assign this operation to a specific worker thread, having less than normal priority.
In such a way, the main thread is ready to handle other user commands. By assigning to the worker thread a less than normal priority, the user interface remains almost just as fast.
Strictly speaking, this guidelines does not improves the speed of the application, but only its responsiveness. Though, this is perceived by users as a speed improvement.
Multiple worker threads [edit]
In a multicore system, if you can split an operation in several threads, use as many worker threads as are the processor cores.
In such a way, every core can process a worker thread. If the worker threads are more than the cores, there would be a lot of thread switching, and this would slow down the operation. The main thread does not slow down the operation, as it is almost inactive.
Use of multi-threaded libraries [edit]
If you are developing a single-threaded application, don't use libraries designed only for multi-threaded applications.
The techniques to make thread-safe a library may have memory and time overhead. If you don't use threads, avoid to pay their cost.
Creation of multi-threaded libraries [edit]
If you are developing a library, handle correctly the case it is used by multi-threaded applications, but optimize also the case it is used by single-threaded applications.
The techniques to make thread-safe a library may have memory and time overhead. If the users of your library don't use threads, avoid forcing your users to pay the cost of threads.
Mutual exclusion [edit]
Use mutual exclusion primitives only when several threads access concurrently the same data, and at least one of the accesses is for writing.
Mutual exclusion primitives have a overhead.
If you are sure that in a given period no thread is writing in a memory area, there is no need to synchronize read accesses for such area.
This page may need to be