Re: MFC, Threads, PostMessage, and Reentrant WindowProc

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



tim.howells@xxxxxxxxxxxxx wrote:
Help!!!! I am struggling trying to cope with thread problems in
a MFC app. Due to MFC not being thread-safe, I am using
PostMessage to dispatch processing to the main thread in
cases where I would otherwise run into problems - for example
when I actually want to draw something on the screen. This
generally seems to work, but I can get deadlocks sometimes
in the main thread for no apparent reason.

I am using Visual C++ and I can examine each thread in the
debugger when a deadlock occurs. There is no apparent
resource cycle - just a normal lock in the main thread following
on after a PostMessage from a worker thread.

Now I am wondering if there is a really fundamental problem here.
Is it safe to lock any resource in WindowProc or any function
call tracing back to WindowProc? Since WindowProc is reentrant
you could get a deadlock simply by locking a resource and then
running into the same lock again in a reentrant call to WindowProc.

I can see how you might get in trouble this way if you don't unlock shortly after you locked. Why not just lock, copy the resource, then unlock immediately? Or even better, avoid locking the main thread at all by passing the data with the message by copying it to heap and passing the pointer in wparam/lparam.

--
Scott McPhillips [VC++ MVP]

.



Relevant Pages

  • Re: MFC, Threads, PostMessage, and Reentrant WindowProc
    ... Due to MFC not being thread-safe, ... on after a PostMessage from a worker thread. ... Is it safe to lock any resource in WindowProc or any function ...
    (microsoft.public.vc.mfc)
  • Re: MFC, Threads, PostMessage, and Reentrant WindowProc
    ... Due to MFC not being thread-safe, ... on after a PostMessage from a worker thread. ... What do you mean a "normal lock"? ... Is it safe to lock any resource in WindowProc or any function ...
    (microsoft.public.vc.mfc)
  • Re: MFC, Threads, PostMessage, and Reentrant WindowProc
    ... Due to MFC not being thread-safe, ... on after a PostMessage from a worker thread. ... Is it safe to lock any resource in WindowProc or any function call tracing back to WindowProc? ...
    (microsoft.public.vc.mfc)
  • Re: MFC, Threads, PostMessage, and Reentrant WindowProc
    ... i donot see any reason of deadlock if windows message is posted via ... PostMessage to dispatch processing to the main thread in ... Is it safe to lock any resource in WindowProc or any function ...
    (microsoft.public.vc.mfc)
  • Re: threading - Monitor.Wait/Pulse
    ... don't get with WaitHandles is that it releases the Lock on the Object you ... You would probably also need to use either a WaitHandle, ... End SyncLock ... will thread 3 then get the resource or will thread 1 ...
    (microsoft.public.dotnet.general)