Is getCurrentThreadId() realtime safe?


#1

On mac at least, getCurrentThreadId() resolves into a call to pthread_self(), which is a system function. That function is called by the function that in turns determines if we are in the message thread or not.

The dogma says that system functions must not be called from the realtime (audio) thread because they aren’t guaranteed to return in a predictable (short) time.

I think it would be reasonable that a function used to check whether we’re in the message thread should be callable from the realtime thread, right?
But given its current implementation, that seems to go against the dogma.

What should we do to check whether we’re in the message thread, with code that could potentially be called from the audio thread?


#2

I don’t think it’s correct that system functions are necessarily non-realtime safe. I think you might be confusing this with system calls which usually incur in a context switch and hence are not realtime safe.

I’m not 100% sure about macOS, but on Linux pthread_self is definitely not a system call. In fact, it’s just a move instructions which copies the thread id from a pre-determined memory location which is filled out by the kernel when the thread is launched (see here). So pthread_self is realtime safe. I’d be surprised if this is any different on macOS.

Many other system functions (like most of the mutex function) are also not system calls. But may call a system call when, for example, they decide to yield. A try lock, for example, is realtime safe although it uses a system function (but not a system call).

On linux you can check which system calls your app is using by running it with strace.