pthread_mutex_lock错误

时间:2011-08-04 13:55:01

标签: c++ c linux networking pthreads

#include "MutexCondition.h"

bool MutexCondition::init(){
    printf("MutexCondition::init called\n");
    pthread_mutex_init(&m_mut, NULL);
    pthread_cond_init(&m_con, NULL);
    return true;
}

bool MutexCondition::destroy(){
    pthread_mutex_destroy(&m_mut);
    pthread_cond_destroy(&m_con);
    return true;
}

bool MutexCondition::lock(){
    pthread_mutex_lock(&m_mut);
    return true;
}

bool MutexCondition::unLock(){
    pthread_mutex_unlock(&m_mut);
    return true;
}

bool MutexCondition::wait(){
    pthread_cond_wait(&m_con, &m_mut);
    return true;
}

bool MutexCondition::signal(){
    pthread_cond_signal(&m_con);
    return true;
}

我正在进行网络编程,我有这个和Sound类,它扩展了MutexCondition

#ifndef SOUND_H_
#define SOUND_H_

#include <list>
#include "SoundMetaData.h"
#include "SoundSignature.h"
#include "../MutexCondition.h"

using namespace std;

class Sound : public MutexCondition{

private:
    SoundMetaData *m_metaData;
    list<SoundSignature*> m_soundSignatureList;

public:
    Sound(SoundMetaData *metaData);
    virtual ~Sound();
    SoundMetaData* getSoundMetaData();
    list<SoundSignature*> getSoundSignatureList();

    bool addApplication(string &application);
    bool removeApplication(string &application);
    void addSoundSignature(SoundSignature* signature);

};

#endif /* SOUND_H_ */

如果我在gdb上运行我的服务器。它从函数getSoundSignatureList上的pthread_mutex_lock()中爆炸。

list<SoundSignature *> Sound::getSoundSignatureList(){
    lock();
    list<SoundSignature*> list(m_soundSignatureList);
    unLock();
    return list;
}

我有一个名为Engine的类,5个不同的线程根据收到的数据包类型创建Engine类。 Engine类中的函数调用getSoundSignatureList类。还有其他任何地方可以调用Engine类。

我不明白它如何在pthred_mutex_lock上爆炸

如何解决这个问题?谢谢你的帮助

编辑.h文件

#ifndef MUTEXCONDITION_H_
#define MUTEXCONDITION_H_

#include <pthread.h>
#include <stdio.h>

class MutexCondition {

private:
    bool init();
    bool destroy();

protected:

    pthread_mutex_t m_mut;
    pthread_cond_t m_con;

public:
    MutexCondition(){
        init();
    }
    virtual ~MutexCondition(){
        destroy();
    }

    bool lock();
    bool unLock();
    bool wait();
    bool signal();

};
#endif /* MUTEXCONDITION_H_ */

1 个答案:

答案 0 :(得分:4)

我想知道你的互斥锁实例是否因为复制或赋值操作而被删除(你甚至可能都不知道)。互斥锁是不可复制的 - 你应该确保通过使copy-ctor和operator =()私有和未实现(或类似技术)来复制你拥有的包装类:

#ifndef MUTEXCONDITION_H_
#define MUTEXCONDITION_H_

#include <pthread.h>
#include <stdio.h>

class MutexCondition {

private:
    bool init();
    bool destroy();

    // idiom to prevent copying: don't implement these
    MutexCondition( MutexCondition const&);
    void operator=( MutexCondition const&);

protected:

    pthread_mutex_t m_mut;
    pthread_cond_t m_con;

public:
    MutexCondition(){
        init();
    }
    virtual ~MutexCondition(){
        destroy();
    }

    bool lock();
    bool unLock();
    bool wait();
    bool signal();

};
#endif /* MUTEXCONDITION_H_ */

另一个注意事项:在我看来,这个类的私有继承可能比公共继承更合适。