Overhead of pthread mutexes?

前端 未结 9 1860
旧时难觅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条回答
  •  生来不讨喜
    2020-12-13 19:09

    I did a similar library and didn't have any trouble with lock performance. (I can't tell you exactly how they're implemented, so I can't say conclusively that it's not a big deal.)

    I'd go for getting it right first (i.e. use locks) then worry about performance. I don't know of a better way; that's what mutexes were built for.

    An alternative for single thread clients would be to use the preprocessor to build a non-locked vs locked version of your library. E.g.:

    #ifdef BUILD_SINGLE_THREAD
        inline void lock () {}
        inline void unlock () {}
    #else
        inline void lock () { doSomethingReal(); }
        inline void unlock () { doSomethingElseReal(); }
    #endif
    

    Of course, that adds an additional build to maintain, as you'd distribute both single and multithread versions.

提交回复
热议问题