我有一个带有成员变量pthread_mutex_t m
的基类B()。当我尝试从派生类锁定互斥锁时,我永远阻止。我打开了GDB并打印了m
的样子,看起来像是乱码(未实例化),但我不确定。
基类
class B
{
protected: //or public!
pthread_mutex_t m;
public:
virtual void lock(); //wrapper for pthread_mutex_lock(&m)
virtual void unlock(); //wrapper
};
派生类
class D : B
{
public:
void foo();
private:
pthread_mutex_t derived_m;
};
这是我无限期阻止的代码。
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}
&amp; derived_m
的GDB print()$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}
答案 0 :(得分:4)
首先应初始化您的互斥锁。有两个选项可以初始化pthread互斥锁。
使用宏
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
使用pthread_mutex_init
功能。
请注意,如果您正在使用启用了c++11
的编译器,则应使用标准std
多线程内容,例如std::mutex
。
良好的开端: