在静态类成员函数上使用互斥体

发布于 2024-10-06 19:42:12 字数 126 浏览 0 评论 0原文

我有一个类至少调用一个线程。类可以有多个线程。该线程需要调用该类的静态成员。每次调用静态成员之前是否必须使用互斥锁,以便其他线程无法同时调用这些成员?我可以对类的所有不同静态成员函数使用相同的互斥变量吗?我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一曲琵琶半遮面シ 2024-10-13 19:42:12

这是一个复杂的、古老的多线程问题,没有简单的答案。这实际上取决于您的使用模式:

  • 这些静态成员是否被频繁访问?
  • 这些成员是否同时被多个线程(而不是几个)同时访问?
  • 哪些静态成员最常用?
  • 多个静态成员是否一起使用?
  • 操作主要涉及阅读吗?

此类问题的答案可以帮助确定应用哪种解决方案。例如,如果您需要吞吐量,则单个互斥锁可能会更有效。如果您想最大限度地减少延迟,独立成员(不需要与其他成员一起使用的成员)上的多个互斥体将有助于最大限度地减少线程之间的争用。如果读取是主要操作,您甚至可能根本不需要互斥体 - 查看 pthread_rwlock

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文