Carbon and thread-safety


The last weeks I have spend some hours here and there to finalize the Carbon/AGL support in Equalizer.

The tricky thing is that Carbon is not thread safe for the functions Equalizer is using. The common consensus is that you should create your windows in the main thread and then fire off your (OpenGL) rendering threads.

Unfortunately I can’t do this in Equalizer, since it already has an established convention on initializing the windows in the rendering threads. Fair enough – global mutex around all window creation and destruction! Err, no, because ReceiveNextEvent is also not thread safe with the window creation calls. And of course ReceiveNextEvent wants to be called from the main thread. Ok, so also protect ReceiveNextEvent? Well, almost – you have to make sure that it doesn’t block indefinitely while holding the mutex.

So what do we end up with? The knowledge that Carbon is the least thread safe window system used by Equalizer, an event loop which polls every 50ms, a serialized window creation which has to wait up to 50ms for each window init, and an API to disable event ‘pumping’ in Equalizer.

Well, I hope the NSGL/Cocoa integration will be less hacky :-/

Advertisements

2 Responses to “Carbon and thread-safety”

  1. Ken Says:

    This is way late, but I just found this post.

    You might try posting a custom event to the main event loop (ReceiveNextEvent). In the handler for that event, signal a semaphore to indicate that the background thread is safe to create a window, then block on a separate semaphore waiting for the background thread to be done. In the background thread, post the event, wait for the semaphore saying it’s safe (and the main thread is blocked in a known state), create your window, then signal the semaphore to let the main thread resume.

    You have to be very careful with exceptions or premature thread-exiting so that the main thread is never permanently stuck. But this should allow you to avoid polling or having a latency as high as 50ms.

  2. eile Says:

    Hi Ken,

    Thanks for your comment. This is indeed a good solution to the problem. It still has some implications performance-wise, i.e., it shouldn’t be used often during rendering, but it’s way better than the current code.

    It’s also not too late, I’ll probably implement it soon. However I should really provide a Cocoa implementation by now. No time, no time. 😦

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: