Programing

Linux C 프로그램에서 pthread의 스레드 ID를 얻는 방법은 무엇입니까?

crosscheck 2020. 10. 14. 07:29
반응형

Linux C 프로그램에서 pthread의 스레드 ID를 얻는 방법은 무엇입니까?


Linux C 프로그램에서 pthread 라이브러리에서 만든 스레드의 스레드 ID를 인쇄하는 방법은 무엇입니까?
예를 들어 : 우리는 다음과 같은 방법으로 프로세스의 PID를 얻을 수 있습니다.getpid()


pthread_self() 함수는 현재 스레드의 스레드 ID를 제공합니다.

pthread_t pthread_self(void);

pthread_self()함수는 호출 스레드의 Pthread 핸들을 반환합니다. pthread_self () 함수는 호출 스레드의 정수 스레드를 리턴하지 않습니다. pthread_getthreadid_np()스레드의 정수 식별자를 반환 하려면을 사용해야 합니다.

노트:

pthread_id_np_t   tid;
tid = pthread_getthreadid_np();

이러한 호출보다 훨씬 빠르지 만 동일한 동작을 제공합니다.

pthread_id_np_t   tid;
pthread_t         self;
self = pthread_self();
pthread_getunique_np(&self, &tid);

뭐? 그 사람은 Linux 특정 및 getpid ()와 동등한 것을 요청했습니다. BSD 나 Apple이 아닙니다. 대답은 gettid ()이며 정수 유형을 반환합니다. 다음과 같이 syscall ()을 사용하여 호출해야합니다.

#include <sys/types.h>
#include <sys/syscall.h>

 ....

 pid_t x = syscall(__NR_gettid);

이것은 리눅스가 아닌 시스템에 이식 할 수는 없지만 threadid는 직접 비교할 수 있고 획득하는 데 매우 빠릅니다. 일반 정수처럼 인쇄 할 수 있습니다 (예 : LOG).


pid_t tid = syscall(SYS_gettid);

Linux는 스레드의 ID를 얻을 수 있도록 이러한 시스템 호출을 제공합니다.


당신이 사용할 수있는 pthread_self()

부모 pthread_create()는가 성공적으로 실행 된 후 스레드 ID를 알게 되지만 스레드를 실행하는 동안 스레드 ID에 액세스하려면 함수를 사용해야합니다 pthread_self().


다른 답변에서 언급했듯이 pthreads는 통합 스레드 ID를 검색하는 플랫폼 독립적 인 방법을 정의하지 않습니다.

Linux 시스템에서는 다음과 같이 스레드 ID를 얻을 수 있습니다.

#include <sys/types.h>
pid_t tid = gettid();

많은 BSD 기반 플랫폼에서이 답변 https://stackoverflow.com/a/21206357/316487 은 이식 불가능한 방법을 제공합니다.

그러나 스레드 ID가 필요하다고 생각하는 이유가 제어하는 ​​다른 스레드와 동일한 스레드에서 실행 중인지 또는 다른 스레드에서 실행 중인지 알기 위해서라면이 방법에서 몇 가지 유틸리티를 찾을 수 있습니다.

static pthread_t threadA;

// On thread A...
threadA = pthread_self();

// On thread B...
pthread_t threadB = pthread_self();
if (pthread_equal(threadA, threadB)) printf("Thread B is same as thread A.\n");
else printf("Thread B is NOT same as thread A.\n");

메인 스레드에 있는지 알아야하는 경우이 질문에 대한 답변에 문서화 된 추가 방법이 있습니다. pthread_self가 프로세스의 메인 (첫 번째) 스레드인지 어떻게 알 수 있습니까? .


이 한 줄은 pid, 각 threadid 및 spid를 제공합니다.

 printf("before calling pthread_create getpid: %d getpthread_self: %lu tid:%lu\n",getpid(), pthread_self(), syscall(SYS_gettid));

pthread_getthreadid_np내 Mac OS x에 없었습니다. pthread_t불투명 한 유형입니다. 머리를 치지 마십시오. 그것을 할당하고 void*좋다고 부르십시오. 당신이해야하는 경우 printf사용합니다 %p.


스레드 ID를 얻는 또 다른 방법이 있습니다. 스레드를 만드는 동안

int pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * (*start_routine)(void *), void *arg);

function call; the first parameter pthread_t * thread is actually a thread id (that is an unsigned long int defined in bits/pthreadtypes.h). Also, the last argument void *arg is the argument that is passed to void * (*start_routine) function to be threaded.

You can create a structure to pass multiple arguments and send a pointer to a structure.

typedef struct thread_info {
    pthread_t thread;
    //...
} thread_info;
//...
tinfo = malloc(sizeof(thread_info) * NUMBER_OF_THREADS);
//...
pthread_create (&tinfo[i].thread, NULL, handler, (void*)&tinfo[i]);
//...
void *handler(void *targs) {
    thread_info *tinfo = targs;
    // here you get the thread id with tinfo->thread
}

I think not only is the question not clear but most people also are not cognizant of the difference. Examine the following saying,

POSIX thread IDs are not the same as the thread IDs returned by the Linux specific gettid() system call. POSIX thread IDs are assigned and maintained by the threading implementation. The thread ID returned by gettid() is a number (similar to a process ID) that is assigned by the kernel. Although each POSIX thread has a unique kernel thread ID in the Linux NPTL threading implementation, an application generally doesn’t need to know about the kernel IDs (and won’t be portable if it depends on knowing them).

Excerpted from: The Linux Programming Interface: A Linux and UNIX System Programming Handbook, Michael Kerrisk

IMHO, there is only one portable way that pass a structure in which define a variable holding numbers in an ascending manner e.g. 1,2,3... to per thread. By doing this, threads' id can be kept track. Nonetheless, int pthread_equal(tid1, tid2) function should be used.

if (pthread_equal(tid1, tid2)) printf("Thread 2 is same as thread 1.\n");
else printf("Thread 2 is NOT same as thread 1.\n");

Platform-independent way (starting from c++11) is:

#include <thread>

std::this_thread::get_id();

참고URL : https://stackoverflow.com/questions/21091000/how-to-get-thread-id-of-a-pthread-in-linux-c-program

반응형