[haiku-3rdparty-dev] Re: Problem sending/receiving app defined msgs

  • From: Ingo Weinhold <ingo_weinhold@xxxxxx>
  • To: haiku-3rdparty-dev@xxxxxxxxxxxxx
  • Date: Sun, 05 Dec 2010 15:28:50 +0100

On 2010-12-05 at 14:15:49 [+0100], Axel Dörfler <axeld@xxxxxxxxxxxxxxxx> 
wrote:
> Using the window as pointer is indeed not thread-safe - creating a
> BMessenger out of it is, though.

Formulated as generally as that the statement isn't quite accurate. In both 
cases the how is relevant. Only dereferencing the window pointer is 
universally unsafe (unless, e.g. by locking, it has been ensured first that 
the window exists and won't go away, of course).

There are several methods that can be invoked, which don't dereference the 
pointer uncheckedly and are thus safe to be called using the pointer. Most 
relevantly for this discussion PostMessage(), but also Lock() (which 
returns false in case the window is already toast) and all methods that 
first call Lock() and check its return value.

It is important to note that BMessenger(window) is an *unsafe* call, since 
the window is passed in as a BHandler* which has to be dereferenced to get 
the respective looper. BMessenger(NULL, window) is safe, but also has a 
different semantics (targeting the preferred handler which is not 
necessarily the window). Unlike window->PostMessage(..., window) using 
BMessenger(window, window) is unsafe in the current Haiku implementation 
(though that could be changed).

While using a potentially invalid window pointer with PostMessage() or the 
NULL-BHandler* BMessenger() constructor is safe in that it won't crash, it 
still has an issue: If the window was deleted and in the meantime a new 
BWindow (or BLooper or any derived class) has been created at the same 
address in memory, the message will be sent to the new object. The only 
really safe method is to create a BMessenger as long as the window object 
is still valid and use that for sending messages. After the destruction of 
the window sending messages via the messenger will simply fail.

CU, Ingo

Other related posts: