How to tell if executing on the main thread ?
19/06/04 09:35
How can I tell if the currently executing code is on the main thread or a secondary thread?
1. using the pthread function pthread_main_np(), returning an int. However, the current man pages for pthread under Darwin/OS X are incomplete and don't contain the doc for this function. From the FreeBSD man pages:
PTHREAD_MAIN_NP(3) FreeBSD Library Functions Manual PTHREAD_MAIN_NP(3)
NAME
pthread_main_np -- identify the initial thread
LIBRARY
Reentrant C Library (libc_r, -pthread)
SYNOPSIS
#include
int
pthread_main_np(void);
DESCRIPTION
The pthread_main_np() function is used in userland threads environment to
identify the initial thread. Its semantics is similar to the Solaris's
thr_main() function.
RETURN VALUES
The pthread_main_np() function returns 1 if the calling thread is the
initial thread, 0 if the calling thread is not the initial thread, and -1
if the thread's initialization has not yet completed.
SEE ALSO
pthread_create(3), pthread_equal(3), pthread_self(3)
AUTHORS
This manual page was written by Alexey Zelkin.
FreeBSD 4.9 February 13, 2003 FreeBSD 4.9
N.B. Under Darwin/Mac OS X, the included file should be pthread.h, not pthread_np.h.
2. implement an extension of the NSThread class that will save the [NSThread currentThread] result in a global variable at load time (in + (void)didLoad for example), so that you can compare to the current thread later. Basically:
static NSThread *sMainThread = nil ;
+ (void)didLoad // or initialize
{
sMainThread = [NSThread currentThread] ;
}
+ (BOOL)inMainThread
{
return [NSThread currentThread] == sMainthread ;
}
A more sophisticated version exists in the OmniGroup's OmniFoundation framework.
PTHREAD_MAIN_NP(3) FreeBSD Library Functions Manual PTHREAD_MAIN_NP(3)
NAME
pthread_main_np -- identify the initial thread
LIBRARY
Reentrant C Library (libc_r, -pthread)
SYNOPSIS
#include
int
pthread_main_np(void);
DESCRIPTION
The pthread_main_np() function is used in userland threads environment to
identify the initial thread. Its semantics is similar to the Solaris's
thr_main() function.
RETURN VALUES
The pthread_main_np() function returns 1 if the calling thread is the
initial thread, 0 if the calling thread is not the initial thread, and -1
if the thread's initialization has not yet completed.
SEE ALSO
pthread_create(3), pthread_equal(3), pthread_self(3)
AUTHORS
This manual page was written by Alexey Zelkin
FreeBSD 4.9 February 13, 2003 FreeBSD 4.9
2. implement an extension of the NSThread class that will save the [NSThread currentThread] result in a global variable at load time (in + (void)didLoad for example), so that you can compare to the current thread later. Basically:
static NSThread *sMainThread = nil ;
+ (void)didLoad // or initialize
{
sMainThread = [NSThread currentThread] ;
}
+ (BOOL)inMainThread
{
return [NSThread currentThread] == sMainthread ;
}
A more sophisticated version exists in the OmniGroup's OmniFoundation framework.