using mutexes on static class member functions
I have a Class that calls at least one thread. The Class can have many threads. This thread needs to call static members of the Class. Do I have to use a mutex before to each call to static members, so other threads can't call the members at the same time? Can I use the same开发者_JAVA百科 mutex variable for all the different static member functions of the Class? I'm using the pthreads library.
This is a complicated, age-old multithreading question with no straightforward answer. It really depends on your usage patterns:
- Are these static members accessed a lot?
- Are these members simultaneously accessed by several threads at once (as opposed to just a couple)?
- Which static members are used the most?
- Are multiple static members used together?
- Do the operations primarily involve reading?
The answers to questions like these can help determine which solution to apply. If you need throughput, for instance, a single mutex can be more efficient. If you want to minimize latency, multiple mutexes on independent members (those that don't need to be used with another) will help minimize contention between threads. If reading is the main action, you might not even want a mutex at all – check out pthread_rwlock
.
精彩评论