Re: synchronizing mouse button events with a thread function
On Aug 1, 8:38 am, wanwan <ericwa...@yahoo.com> wrote:
I have an unusual way of using the lock, but I'm not sure if it is a
good approach. Suppose I need to synchronize mouse button event with a
function from another process, I'm thinking of using the following
method:
CMutex m_mtx;
CSingleLock m_MouseEventLock;
OnLButtonDown
{
m_MouseEventLock = CSingleLock(m_mtx);
m_MouseEventLock.Lock();
...
}
OnLButtonUp
{
...
m_MouseEventLock.Unlock();
...
}
ThreadProcFunc
{
...
CSingleLock lock(m_mtx);
lock.Lock();
...
lock.Unlock();
}
My concern here is reusing the lock variable in the mouse button
event. Is it allowed. I'm asking because conventionally, the lock
variable is declared locally in a function. In my case, I need to
declare in the class scope.
Or if anyone has a better algorithm than mine, please advise.
I would use a manual reset event instead of the mutex because the
thread don't have to lock/unlock it (just check the state). Anyway,
this is a matter of taste.
Example:
CEvent m_event(TRUE, TRUE); // Manual Reset Event, Signaled State
OnLButtonDown
{
....
m_event.ResetEvent(); // Pause threads
...
}
OnLButtonUp
{
...
m_event.SetEvent(); // Continue threads
...
}
ThreadProcFunc
{
...
::WaitForSingleObject(m_event, INFINITE); // maybe m_event.Lock()
works too but I don't know whats under the hood happen else
...
}
Just be aware that if the user moves the mouse cursor out of your
window and releases the mousbutton your application will not receive
the button-up-message and unlock your mutex. If you want to avoid
this, your window needs to capture the mouse events even if it is
outside the window.