How to set the name of a thread in Linux pthreads?

前端 未结 3 642
独厮守ぢ
独厮守ぢ 2020-11-28 03:59

Is there any way of setting the name of a thread in Linux?

My main purpose is it would be helpful while debugging, and also nice if that name was exposed through e.g

3条回答
  •  时光说笑
    2020-11-28 04:38

    As of glibc v2.12, you can use pthread_setname_np and pthread_getname_np to set/get the thread name.

    These interfaces are available on a few other POSIX systems (BSD, QNX, Mac) in various slightly different forms.

    Setting the name will be something like this:

    #include   // or maybe  for some OSes
    
    // Linux
    int pthread_setname_np(pthread_t thread, const char *name);
    
    // NetBSD: name + arg work like printf(name, arg)
    int pthread_setname_np(pthread_t thread, const char *name, void *arg);
    
    // FreeBSD & OpenBSD: function name is slightly different, and has no return value
    void pthread_set_name_np(pthread_t tid, const char *name);
    
    // Mac OS X: must be set from within the thread (can't specify thread ID)
    int pthread_setname_np(const char*);
    

    And you can get the name back:

    #include   // or  ?
    
    // Linux, NetBSD:
    int pthread_getname_np(pthread_t th, char *buf, size_t len);
    // some implementations don't have a safe buffer (see MKS/IBM below)
    int pthread_getname_np(pthread_t thread, const char **name);
    int pthread_getname_np(pthread_t thread, char *name);
    
    // FreeBSD & OpenBSD: dont' seem to have getname/get_name equivalent?
    // but I'd imagine there's some other mechanism to read it directly for say gdb
    
    // Mac OS X:
    int pthread_getname_np(pthread_t, char*, size_t);
    

    As you can see it's not completely portable between POSIX systems, but as far as I can tell across linux it should be consistent. Apart from Mac OS X (where you can only do it from within the thread), the others are at least simple to adapt for cross-platform code.

    Sources:

    • glibc NEWS (mentions new interfaces in 2.12)
    • glibc nptl/ChangeLog (mentions new interfaces in 2.12)
    • MKS setname / getname
    • IBM setname / getname
    • Mac OS X from /Developer/SDKs/MacOSX10.7.sdk/usr/include/pthread.h
    • QNX setname / getname
    • FreeBSD setname / no getname as far as i can see
    • OpenBSD setname / no getname as far as i can see
    • NetBSD setname / getname

提交回复
热议问题