c++ - Select mutex or dummy mutex at runtime -
I have a class that has been shared between several projects, some of its uses are single-threaded and some are multi-pronged - Threaded single threaded users do not want the overhead of the Mute X locking, and multi-threaded users do not want to lock them and alternatively they want to be able to run in "single-threaded mode". So I would like to be able to choose between real and "dummy" mutates on runtime.
Ideally, I have a shared_ptr
unique_lock & lt; Something & gt; Guard (* mutex); ... key segment ...
is now a signals2 :: dummy_mutex
but it does not share a common base class with boost :: Does Mutex
So, what is a great way to choose between real mutes and a dummy mutux (either in signal 2 or something else)?
And, before choosing options:
- I can select an implementation on timing compilation, but preprocessor macros are poor and painful to maintain project configuration We have to
- In a multi-threaded environment, class users do not want to take responsibility for locking the class's use instead of the internal locking.
- There are lots of APIs and there are current uses for a "thread-safe cover" for a practical solution.
How about something like this? It has not been tested but should be closer to recovery. You can consider template class as a value instead of a pointer if your mute supports the creation of the right type otherwise you may be the expert in the MyMutex class to get value behavior. Are there.
Apart from this, it is not careful about duplication or destruction. I leave it as a practice for the reader;) (shared_ptr) or indicator should correct it)
Oh, and code will use RAII instead of explicit lock / unlock ... but this is a different question. I think what is unique_lock in your code?
struct IMutex {virtual ~ IMutex () {} Virtual Zero Lock () = 0; Virtual Boole try_lock () = 0; Virtual Zero Unlock () = 0; }; Template & lt; Typename T & gt; Classmaymute: Public Imtax {Public: Maimutex (TT): T_ (T) {} Zero Lock () {T _-> Lock (); } Bool try_lock () {Return T _-> Try_lock (); } Zero unlock () {t _-> Unlock (); } Conserved: T * t_; }; IMutex * createMutex () {if (Mathithradeed)} {New Mimeoot XUt; Promotion: Mute X & gt; (New boost :: mute x); } Other {new Mimeet X & lift; Signal 2 :: Dummy_Mutex & gt; (New signal 2 :: dummy_mutex); }} Int main () {IMutex * mutex = createMutex (); ... {unique_lock & lt; IMutex & gt; Guard (* mutes); ...}}
Comments
Post a Comment