Overhead of pthread mutexes?

前端 未结 9 1842
旧时难觅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:19

    Well a suboptimal but simple approach is to place macros around your mutex locks and unlocks. Then have a compiler / makefile option to enable / disable threading.

    Ex.

    #ifdef THREAD_ENABLED
    #define pthread_mutex_lock(x) ... //actual mutex call
    #endif
    
    #ifndef THREAD_ENABLED
    #define pthread_mutex_lock(x) ... //do nothing
    #endif
    

    Then when compiling do a gcc -DTHREAD_ENABLED to enable threading.

    Again I would NOT use this method in any large project. But only if you want something fairly simple.

    0 讨论(0)
  • 2020-12-13 19:20

    All modern thread implementations can handle an uncontended mutex lock entirely in user space (with just a couple of machine instructions) - only when there is contention, the library has to call into the kernel.

    Another point to consider is that if an application doesn't explicitly link to the pthread library (because it's a single-threaded application), it will only get dummy pthread functions (which don't do any locking at all) - only if the application is multi-threaded (and links to the pthread library), the full pthread functions will be used.

    And finally, as others have already pointed out, there is no point in protecting a getter method for something like isActive with a mutex - once the caller gets a chance to look at the return value, the value might already have been changed (as the mutex is only locked inside the getter method).

    0 讨论(0)
  • 2020-12-13 19:20

    This is a bit off-topic but you seem to be new to threading - for one thing, only lock where threads can overlap. Then, try to minimize those places. Also, instead of trying to lock every method, think of what the thread is doing (overall) with an object and make that a single call, and lock that. Try to get your locks as high up as possible (this again increases efficiency and may /help/ to avoid deadlocking). But locks don't 'compose', you have to mentally at least cross-organize your code by where the threads are and overlap.

    0 讨论(0)
提交回复
热议问题