programing

Linux pthreads에서 스레드 이름을 설정하는 방법

copyandpastes 2022. 8. 16. 21:50
반응형

Linux pthreads에서 스레드 이름을 설정하는 방법

Linux에서 스레드 이름을 설정하는 방법이 있습니까?

디버깅을 할 때 도움이 되는 것이 주된 목적입니다.또, 예를 들면, 그 이름이 공개되면 좋을 것입니다./proc/$PID/task/$TID/...

glibc v2.12 이후로는pthread_setname_np그리고.pthread_getname_np스레드 이름을 설정/취득합니다.

이러한 인터페이스는 몇 가지 다른 POSIX 시스템(BSD, QNX, Mac)에서 약간 다른 다양한 형태로 사용할 수 있습니다.

이름 설정은 다음과 같습니다.

#include <pthread.h>  // or maybe <pthread_np.h> 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*);

이름을 다시 찾을 수 있습니다.

#include <pthread.h>  // or <pthread_np.h> ?

// 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);

보시다시피 POSIX 시스템 간에는 완전히 이식할 수 없지만 Linux 에는 일관성이 있어야 합니다.Mac OS X(스레드 내에서만 가능)를 제외하고, 다른 OS는 최소한 크로스 플랫폼 코드에 맞게 조정하기 쉽습니다.

출처:

를 사용합니다.prctl(2)옵션으로 기능하다PR_SET_NAME(문서 참조).

이전 버전의 문서는 약간 혼란스럽다는 점에 유의하십시오.그들은 말한다

호출 프로세스의 프로세스 이름 설정

그러나 스레드는 Linux에서는 Light Weight Process(LWP; 경량 프로세스)이기 때문에 이 경우 스레드는 1개의 프로세스입니다.

스레드 이름은 다음과 같이 표시할 수 있습니다.ps -o cmd또는 다음 항목과 함께:

cat /proc/$PID/task/$TID/comm

또는 그 사이에()cat /proc/$PID/task/$TID/stat:

4223 (kjournald) S 1 1 1 0...

또는 GDB에서info threads큰따옴표 사이:

* 1    Thread 0x7ffff7fc7700 (LWP 6575) "kjournald" 0x00007ffff78bc30d in nanosleep () at ../sysdeps/unix/syscall-template.S:84                                                                                  

사전 매핑을 생성하여 직접 구현할 수 있습니다.pthread_t로.std::stringpthread_self() 결과를 현재 스레드에 할당하는 이름과 관련짓습니다.이 경우 뮤텍스 또는 기타 동기화 프리미티브를 사용하여 여러 스레드가 사전을 동시에 수정하는 것을 방지해야 합니다(사전 구현이 이미 이를 수행하지 않는 한).스레드 고유의 변수(pthread_key_create, pthread_setspecific, pthread_getspecificpthread_key_delete 참조)를 사용하여 현재 스레드의 이름을 저장할 수도 있습니다.단, (사전을 사용하여) 모든 스레드 ID/이름 쌍에서 반복할 수 있습니다.읽다)

언급URL : https://stackoverflow.com/questions/2369738/how-to-set-the-name-of-a-thread-in-linux-pthreads

반응형