在静态类成员函数上使用互斥体
我有一个类至少调用一个线程。类可以有多个线程。该线程需要调用该类的静态成员。每次调用静态成员之前是否必须使用互斥锁,以便其他线程无法同时调用这些成员?我可以对类的所有不同静态成员函数使用相同的互斥变量吗?我正在使用 pthreads 库。
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 mutex variable for all the different static member functions of the Class? I'm using the pthreads library.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个复杂的、古老的多线程问题,没有简单的答案。这实际上取决于您的使用模式:
此类问题的答案可以帮助确定应用哪种解决方案。例如,如果您需要吞吐量,则单个互斥锁可能会更有效。如果您想最大限度地减少延迟,独立成员(不需要与其他成员一起使用的成员)上的多个互斥体将有助于最大限度地减少线程之间的争用。如果读取是主要操作,您甚至可能根本不需要互斥体 - 查看
pthread_rwlock
。This is a complicated, age-old multithreading question with no straightforward answer. It really depends on your usage patterns:
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
.