Lock through inheritance, not composition

In most codes that I wrote or looked at, locking is done using composition, where the class owns a critical sector or mutex:

class MyClass
{
    Mutex mMutex;
};

and when mutable members can be accessed through multiple threads, we get and release the lock via RAII as follows:

void MyClass::Method()
{
    Lock lock(mMutex);
    // ...
}

Today I looked at the code in which the code was blocking through inheritance, for example:

class MyClass : public Mutex
{
    // ...
};

And blocking is done using the "lock" of the class itself:

void MyClass::Method()
{
    Lock lock(this);
    // ...
}

Are there any advantages or disadvantages to this approach? Or is it just a style issue?

+3
source share
2 answers

, - . , Mutex (, Mutex , ), , , , (, , Mutex ).

, , - , , - , MyClass Mutex. , , . Mutex ( ), , .

, , , .NET, "". , .NET lock(this), , , .

+4

. MyClass - , Mutex? , , MyClass Mutex ( MyClass to Mutex "is-a" ).

:

MyClass x;
Lock lock(x);
x.Method();   // uh oh.
+6

Source: https://habr.com/ru/post/1779904/


All Articles