Search code examples
androidandroid-ndkpthreads

How to obtain thread name in android ndk


In my Android project, I'm using std::thread. I use the same C++ code also in some Linux and OSX projects.

For debugging purpose, I want to assign human-readable thread names and I do that by calling pthread_setname_np() (because lack of std::thread::set_name()).

In case of later debug output, I try to obtain the current thread name by calling pthread_getname_np() and this works e.g. on Linux target.

But for my surprise, there is no pthread_getname_np() in Android Ndk pthread.h, not in e.g. ndk-bundle/platforms/android-19/arch-arm/usr/include/pthread.h nor in ndk-bundle/platforms/android-21/arch-arm/usr/include/pthread.h

A stupid trying with a forward declaration like:

extern "C" int pthread_getname_np(pthread_t, char*, size_t);

fails with a linker error (as expected).

Any idea how to obtain the human readable name of the current thread in Android from C/C++ code?


Solution

  • You can see how Dalvik sets them in dalvik/vm/Thread.cpp. It uses pthread_setname_np() if available, prctl(PR_SET_NAME) if not. So if pthread_getname_np() isn't available -- and bear in mind that "np" means "non-portable" -- you can use prctl(PR_GET_NAME) to get a 16-byte null-terminated string under Linux.

    You can find other bits by fishing around in /proc entries.

    If you have specific requirements for the size and format of the name then you may want to define a pthread key and tuck it into thread-local storage. It's more work, but it's consistent and portable.