Overhead of pthread mutexes?

前端 未结 9 1853
旧时难觅i
旧时难觅i 2020-12-13 18:46

I\'m trying to make a C++ API (for Linux and Solaris) thread-safe, so that its functions can be called from different threads without breaking internal data structures. In m

9条回答
  •  Happy的楠姐
    2020-12-13 19:01

    A mutex requires an OS context switch. That is fairly expensive. The CPU can still do it hundreds of thousands of times per second without too much trouble, but it is a lot more expensive than not having the mutex there. Putting it on every variable access is probably overkill.

    It also probably is not what you want. This kind of brute-force locking tends to lead to deadlocks.

    do you know better ways to protect such variable accesses?

    Design your application so that as little data as possible is shared. Some sections of code should be synchronized, probably with a mutex, but only those that are actually necessary. And typically not individual variable accesses, but tasks containing groups of variable accesses that must be performed atomically. (perhaps you need to set your is_active flag along with some other modifications. Does it make sense to set that flag and make no further changes to the object?)

提交回复
热议问题