Hi, I'm tring to use lock_guard, but I have some doubts... I have a method called OnDataReceived() which is called by another class through a signal. void ATDispatcher::OnDataReceived() { boost::lock_guardboost::mutex lock(_mut); // Data received from RS232 _device.GetData(_buffer); // .... CODE .... // unlock the mutex before notifications lock.~lock_guard(); signal_OnData(); } The first time it's called, it works fine. The second time the flow locks on the creation of the lock object. In the caller class I have solved this declaring the lock in this manner: boost::mutex::scoped_lock lock(_mutex); lock.unlock(); while (true) { //main loop lock.lock(); // saving data to vector _read_buffer.append(buf, rd); //Unlock the mutex lock.unlock(); signal_OnData(); } but here because there is the worker thread loop, while in the called class there is no loop. Thanks for suggestions. Daniele.
2009/3/10 Daniele Barzotti
Hi,
I'm tring to use lock_guard, but I have some doubts...
I have a method called OnDataReceived() which is called by another class through a signal.
void ATDispatcher::OnDataReceived() { boost::lock_guardboost::mutex lock(_mut);
// Data received from RS232 _device.GetData(_buffer);
// .... CODE ....
// unlock the mutex before notifications lock.~lock_guard();
You should not manually call destructors of automatic (stack allocated) objects. It's an Undefined Behavior and in practice it usually causes destructor to be called twice. You might want to put lock_guard in additional scope. { boost::lock_guardboost::mutex lock(_mut); // Data received from RS232 _device.GetData(_buffer); // .... CODE .... } // Destructor of lock is called here. signal_OnData(); } Roman Perepelitsa.
Roman Perepelitsa wrote:
You should not manually call destructors of automatic (stack allocated) objects. It's an Undefined Behavior and in practice it usually causes destructor to be called twice. You might want to put lock_guard in additional scope.
{ boost::lock_guardboost::mutex lock(_mut); // Data received from RS232 _device.GetData(_buffer); // .... CODE .... } // Destructor of lock is called here. signal_OnData(); }
Roman Perepelitsa.
Thanks for the suggestion Roman! Daniele.
On Tue, Mar 10, 2009 at 8:51 AM, Roman Perepelitsa
[...] You should not manually call destructors of automatic (stack allocated) objects. It's an Undefined Behavior and in practice it usually causes destructor to be called twice. You might want to put lock_guard in additional scope.
{ boost::lock_guardboost::mutex lock(_mut); // Data received from RS232 _device.GetData(_buffer); // .... CODE .... } // Destructor of lock is called here. signal_OnData(); }
Or use unique_lock or scoped_lock: boost::mutex::scoped_lock lock(_mut); .... lock.unlock(); signal_OnData();
participants (3)
-
Daniele Barzotti
-
Oliver Seiler
-
Roman Perepelitsa