GUIs and the Main Thread

You got this backwards. This isn't a definition of the main thread it just tells you what that thread is supposed to be doing.


I've experimented on OS X 10.10.5 a bit with this sample GTK app. It shows a window with a single button. Then I added another thread into the picture:

fn main() {
    let _ = thread::spawn(|| {
        real_main();
    }).join();
}

The app didn't crash but instead of the window I saw a solid white rectangle, which didn't respond to any actions except dragging it by the bar where the caption would have been. This is consistent with the claims that you gotta do everything in the fn main() thread.

For completeness I would also like to try out the following advice from Using POSIX Threads in a Cocoa Application:

The existing Cocoa bindings don't seem to support this so I could use some help with this.

Hmm... okay. The thread with the event loop actually has to be the runtime startup thread. Annoying, but understandable.

Adding support to the standard library for checking whether a thread is the runtime startup thread would be very easy. Actually, you can basically do it now: std::thread::current().name() == Some("<main>").

3 Likes

For the record, you can use this on OS X to accurately determine if you're on the main thread (even if, say, you're writing a library with no main function):

/* returns non-zero if the current thread is the main thread */
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0)
int pthread_main_np(void);
2 Likes