In keeping with my tradition of random experiments of no practical use, I present another edition of “Productive Waste of Time”.
In a Cocoa app, there’s a notion of the main thread. It’s the thread where all events are dispatched. If you don’t create any threads yourself, all your code is going to run in this thread.
The issue of getting a hold of the main thread came up in #macsb. While the Cocoa docs talk a bit about the main thread and what should and should not happen there, they do not give you a way to actually get a handle on it. Daniel Jalkut, whose fault it is for bringing this all up, suggested using pthread_main_np(). While it may work, I looked for a Cocoa-only solution that didn’t assume that pthreads’ notion of a main thread would always align with Cocoa’s.
So, I whipped up this NSThread category to do just that. Just drop it in. No special hooks or hook up needed. It basically just uses -performSelectorOnMainThread:… to set a static var. I didn’t use any locks as I felt the worse that would happen is a bunch of threads set the variable multiple times with the same value. If there’s a subtlety in the memory model that I’m missing here, let me know. Also, if the main thread is tied up, you could potentially tie up other threads as well. Also also, if the main thread exits, I’m guessing bad stuff will happen though it will happen regardless of the code here.
@interface NSThread (MainThreadAdditions)
+ (NSThread *)mainThread;
- (BOOL)isMainThread;
@end
static NSThread *_mainThread;
@implementation NSThread (MainThreadAdditions)
// Only call this from the main thread.
// Actually, do not call this at all. It is done for you.
+ (void)_setMainThread
{
_mainThread = [NSThread currentThread];
}
+ (NSThread *)mainThread
{
if (_mainThread == nil)
{
[self performSelectorOnMainThread:@selector(_setMainThread) withObject:nil waitUntilDone:YES];
}
return _mainThread;
}
- (BOOL)isMainThread
{
return [[NSThread currentThread] isEqual:[NSThread mainThread]];
}
@end
Now, why would you need this? Beats me. It came up in discussion and I decided to roll with it. I provide the code here for your use. It is released under the ‘Splain license. This license says you can do whatever you want with this code under the condition that you ’splain why you need it. Please post here.
Use this code at your own risk. I am not liable for any bad stuff that may happen as the result, directly or indirectly, of using this code. Side-effects may include nausea, dry mouth and brain rash. This is not a suppository.