Atomar94 Atomar94 - 3 years ago 119
C++ Question

Why can't I lock a base class mutex from a derived class?

I have a base class B() with a member variable

pthread_mutex_t m
. When I try to lock the mutex from the derived class I block forever. I opened up GDB and printed what
m
looks like and it seems like gibberish (uninstantiated) but I'm not sure.

Base Class

class B
{
protected: //or public!
pthread_mutex_t m;

public:
virtual void lock(); //wrapper for pthread_mutex_lock(&m)
virtual void unlock(); //wrapper
};


Derived Class

class D : B
{
public:
void foo();

private:
pthread_mutex_t derived_m;
};


And this is the code I have which blocks indefinitely.

D::foo() {
//for reference below, gdb prints were taken here.

pthread_mutex_lock(&m); //blocks forever
pthread_mutex_lock(&derived_m); //okay
lock(); //blocks forever
}


GDB print() for &m

$1 = {__data = {__lock = -8656, __count = 32767, __owner = 4198302,
__nusers = 0, __kind = 3, __spins = 0, __elision = 0, __list = {
__prev = 0x400fed <__libc_csu_init+77>, __next = 0x0}},
__size = "0\336\377\377\377\177\000\000\236\017@\000\000\000\000\000\003\000\000\000\000\000\000\000\355\017@", '\000' <repeats 12 times>, __align = 140737488346672}


GDB print() for &derived_m

$2 = {__data = {__lock = 0, __count = 0, __owner = -134225560,
__nusers = 32767, __kind = 14, __spins = 0, __elision = 0,
__list = {__prev = 0x400e7f <Logging::Logging(datastruct*)+67>,
__next = 0x7fffffffddc0}},
__size = "\000\000\000\000\000\000\000\000h\341\377\367\377\177\000\000\016\000\000\000\000\000\000\000\177\016@\000\000\000\000\000\300\335\377\377\377\177\000", __align = 0}

Answer Source

Your mutex should be initialized first. There's two options to initialize a pthread mutex.

  • Using the macro

    pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
    
  • Using pthread_mutex_init function.

Please note that if you're using a c++11 enabled compiler, you should use the standard std multithreading stuff, e.g. std::mutex.

Good starts:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download