Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mac OS X: is it possible to imbue a non-main thread to become "The Main Thread" of a process?

I'm having a GUI/threading-related problem under Mac OS X (10.6.7). I'm using the wxWidgets framework (ver. 2.9.1), and it rests upon Cocoa in my case. The application design is like this:

  • thread #1 (a.k.a. "The Main Thread"): enters main(), parses switches, and if necessary, launches another thread (using the POSIX primitives).
  • thread #2 (a.k.a. "The GUI thread"): uses wxEntry to initialize wxWidgets and show the GUI.

Like most other GUI frameworks, Cocoa is not thread-safe, so we make sure to do all GUI calls from within thread #2, passing messages if required. Yet, in that particular case, an assertion is raised from within Cocoa's internals during initialization (from NSUndoManager to be more precise) saying in essence "it's not safe to use me outside the main thread". Even though thread #2 is the main thread as far as anything GUI-related is concerned.

Well, NSUndoManager has to have a way to find out it's running off the main thread (probably using NSThread::isMainThread()). So my question is: is it possible to trick NSUndoManager (and Cocoa in general) about this? And even better, to declare thread #2 being "The Main Thread", with thread #1 becoming a secondary one? Basically, I need an API call like "make the calling thread become the Main One". Undocumented wizardry and Objective C++ is fine, as long as it works on OS X 10.5 as well.

P.P. the code, as it is now, works flawlessly under Windows/Linux/MacOSX+Carbon. Also, redesigning it to change the thread structure would be a huge pain.

like image 625
anrieff Avatar asked May 30 '11 16:05

anrieff


1 Answers

OK, so according to your comment: you basically won't escape refactoring of your code. Most GUI systems use main thread and handle event loops for themselves. But if you say that GUI is optional, maybe it'd better to split your application into two -- worker and GUI. GUI could communicate with worker via numerous ways, depending on platforms/specific needs.

like image 177
John Avatar answered Oct 21 '22 05:10

John