我有一個使用升壓互斥體和鎖像這樣(只相關部分)的自定義類:爲什麼boost :: recursive_mutex不能按預期工作?
template<class T> class FFTBuf
{
public:
FFTBuf();
[...]
void lock();
void unlock();
private:
T *_dst;
int _siglen;
int _processed_sums;
int _expected_sums;
int _assigned_sources;
bool _written;
boost::recursive_mutex _mut;
boost::unique_lock<boost::recursive_mutex> _lock;
};
template<class T> FFTBuf<T>::FFTBuf() : _dst(NULL), _siglen(0),
_expected_sums(1), _processed_sums(0), _assigned_sources(0),
_written(false), _lock(_mut, boost::defer_lock_t())
{
}
template<class T> void FFTBuf<T>::lock()
{
std::cerr << "Locking" << std::endl;
_lock.lock();
std::cerr << "Locked" << std::endl;
}
template<class T> void FFTBuf<T>::unlock()
{
std::cerr << "Unlocking" << std::endl;
_lock.unlock();
}
如果我試圖鎖定不止一次對象更在同一個線程,我得到一個異常( lock_error):
#include "fft_buf.hpp"
int main(void) {
FFTBuf<int> b(256);
b.lock();
b.lock();
b.unlock();
b.unlock();
return 0;
}
這是輸出:
[email protected] $ ./src/test
Locking
Locked
Locking
terminate called after throwing an instance of 'boost::lock_error'
what(): boost::lock_error
zsh: abort ./src/test
這是爲什麼HAP pening?我是否正確理解了一些概念?
這有效,但爲什麼? – Kjir 2010-04-02 13:52:27
那麼boost :: unique_lock的用途是什麼?它簡單地使用互斥鎖有什麼優勢?我猜想,RAII, – Kjir 2010-04-02 14:20:34
。 http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization – 2010-04-02 14:22:48