当前位置: 技术问答>linux和unix
【求助】关于pthread_mutex_t变量的初始化问题
来源: 互联网 发布时间:2016-02-21
本文导语: #include #include class A { public: A(); pthread_mutex_t m; }; A::A():m (PTHREAD_MUTEX_INITIALIZER) { } int main() { return 0; } 编译出现错误: testA.cpp: In constructor `A::A()': testA.cpp:14: parse error before `{' token ...
#include
#include
class A
{
public:
A();
pthread_mutex_t m;
};
A::A():m (PTHREAD_MUTEX_INITIALIZER)
{
}
int main()
{
return 0;
}
编译出现错误:
testA.cpp: In constructor `A::A()':
testA.cpp:14: parse error before `{' token
testA.cpp:14: parse error before `{' token
请问这是什么原因?应该如何初始化呢?
#include
class A
{
public:
A();
pthread_mutex_t m;
};
A::A():m (PTHREAD_MUTEX_INITIALIZER)
{
}
int main()
{
return 0;
}
编译出现错误:
testA.cpp: In constructor `A::A()':
testA.cpp:14: parse error before `{' token
testA.cpp:14: parse error before `{' token
请问这是什么原因?应该如何初始化呢?
|
//lock.h 头文件
#ifndef AUTO_LOCK_H
#define AUTO_LOCK_H
#include
namespace util
{
class LockableObject {
public:
LockableObject(){};
virtual ~LockableObject(){};
virtual void lock() = 0;
virtual void unlock() = 0;
};
class ThreadMutex : public LockableObject {
public:
ThreadMutex();
virtual ~ThreadMutex();
virtual void lock();
virtual void unlock();
private:
pthread_mutex_t m_cs;
};
class AutoLock {
public:
AutoLock(LockableObject* pLockable);
~AutoLock();
private:
LockableObject* m_pLockable;
};
}
#endif
#include "lock.h"
#include
//lock.cpp 头文件
namespace util
{
ThreadMutex::ThreadMutex() {
pthread_mutex_init(&m_cs, NULL);
}
ThreadMutex::~ThreadMutex() {
pthread_mutex_destroy(&m_cs);
}
void ThreadMutex::lock() {
pthread_mutex_lock(&m_cs);
}
void ThreadMutex::unlock() {
pthread_mutex_unlock(&m_cs);
}
AutoLock::AutoLock(LockableObject* pLockable) {
m_pLockable = pLockable;
m_pLockable->lock();
}
AutoLock::~AutoLock() {
m_pLockable->unlock();
}
}
//main.cpp
#include
#include "lock.h"
using namespace util;
int main(int argc, char *argv[])
{
ThreadMutex cs;
AutoLock(cs);
return 0;
}