'pthread_setname_np' was not declared in this scope

跟風遠走 提交于 2021-02-07 22:39:06

问题


I have created multiple threads in my application. I want to assign a name to each pthread so I used pthread_setname_np which worked on Ubuntu but is not working on SUSE Linux.

I googled it and came to know '_np' means 'non portable' and this api is not available on all OS flavors of Linux.

So now I want to do it only if the API is available. How to determine whether the api is available or not ? I need something like this.

#ifdef SOME_MACRO
    pthread_setname_np(tid, "someName");
#endif

回答1:


You can use the feature_test_macro _GNU_SOURCE to check if this function might be available:

#ifdef _GNU_SOURCE
    pthread_setname_np(tid, "someName");
#endif

But the manual states that the pthread_setname_np and pthread_getname_np are introduced in glibc 2.12. So if you are using an older glibc (say 2.5) then defining _GNU_SOURCE will not help.

So it's best to avoid these non portable function and you can easily name the threads yourself as part of your thread creation, for example, using a map between thread ID and a array such as:

pthread_t tid[128];
char thr_names[128][256]; //each name corresponds to on thread in 'tid'

You can check the glibc version using:

getconf GNU_LIBC_VERSION



回答2:


Since this function was introduced in glibc 2.12, you could use:

#if ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
    pthread_setname_np(tid, "someName");
#endif



回答3:


This kind of thing - finding out if a particular function exists in your compilation environment - is what people use GNU Autoconf scripts for.

If your project is already using autoconf, you can add this to your configure source, after the point where you have checked for the pthreads compiler and linker flags:

AC_CHECK_FUNCS(pthread_setname_np)

...and it will define a macro HAVE_PTHREAD_SETNAME_NP if the function exists.



来源:https://stackoverflow.com/questions/30346649/pthread-setname-np-was-not-declared-in-this-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!