C에서 스레드 ID 가져 오기

Jinku Hu 2023년10월12일
  1. pthread_self함수를 사용하여 C에서 스레드 ID 가져 오기
  2. gettid함수를 사용하여 C에서 스레드 ID 가져 오기
  3. thrd_current함수를 사용하여 C에서 스레드 ID 가져 오기
C에서 스레드 ID 가져 오기

이 기사는 C에서 스레드 ID를 얻는 방법에 대한 여러 방법을 보여줍니다.

pthread_self함수를 사용하여 C에서 스레드 ID 가져 오기

스레드는 더 나은 다중 스레드 워크 플로를 지원하기 위해 요즘 더 많은 가상 또는 물리적 코어를 추가하는 경향이 있으므로 최신 CPU에서 성능의 초석입니다. 일반적으로 스레드는 프로세스 (즉, 실행중인 프로그램)에서 단일 제어 흐름으로 표시됩니다. 따라서 스레드는 동시에 실행되고 여러 CPU 코어를 사용하는 프로그램을 형성하는 여러 논리 흐름을 구현하는 데 사용됩니다. POSIX 스레드는 C 프로그램의 스레딩 기능에 액세스하기위한 가장 오래된 표준 인터페이스였습니다. pthread_self는 호출 스레드의 ID를 검색 할 수있는pthreads API에서 제공하는 함수 중 하나입니다. 인수는 0이고 스레드 ID를pthread_t유형 변수로 나타내는 정수를 리턴합니다.

다음 예제 코드에서는 기본 프로그램 (스레드)이printHello함수를 실행하고pthread_exit함수 호출을 사용하여 종료하는 추가 4 개의 스레드를 생성하는 기본 다중 스레드 시나리오를 구현했습니다. 이 프로그램 동안 5 개의 스레드가 실행되고 있으며 지정된 코드 경로가 실행 된 후 모두 종료됩니다. printHello함수에서 모두pthread_self함수를 사용하여 스레드 ID를 인쇄합니다.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#ifndef NUM_THREADS
#define NUM_THREADS 4
#endif

void *printHello(void *threadid) {
  long tid;
  tid = (long)threadid;
  printf("Hello There! thread %ld, pthread ID - %lu\n", tid, pthread_self());
  pthread_exit(NULL);
}

int main(int argc, char const *argv[]) {
  pthread_t threads[NUM_THREADS];
  int rc;
  long t;

  for (t = 0; t < NUM_THREADS; t++) {
    rc = pthread_create(&threads[t], NULL, printHello, (void *)t);
    if (rc) {
      printf("ERORR; return code from pthread_create() is %d\n", rc);
      exit(EXIT_FAILURE);
    }
  }
  pthread_exit(NULL);
}

출력:

Hello There! thread 1, pthread ID - 140388002486016
Hello There! thread 0, pthread ID - 140388010878720
Hello There! thread 2, pthread ID - 140387994093312
Hello There! thread 3, pthread ID - 140387985700608

gettid함수를 사용하여 C에서 스레드 ID 가져 오기

‘gettid’는 C 프로그램에서 함수 래퍼를 사용하여 제공되는 Linux 전용 시스템 호출이며 호출자의 스레드 ID를 반환합니다. 이 함수는pthread_self와 유사한 인수를 취하지 않으며pid_t 유형의 정수 값을 반환합니다. gettid 호출에 의해 반환 된 값은 POSIX 스레드 ID라고하는pthread_self 함수에서 검색된 ID와 동일하지 않습니다. 프로그램이 단일 스레드 인 경우gettidgetpid와 동일한 값을 반환하며 프로세스 ID와 동일합니다.

#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#ifndef NUM_THREADS
#define NUM_THREADS 4
#endif

void *printHello(void *threadid) {
  long tid;
  tid = (long)threadid;
  printf("Hello There! thread %ld, kthread ID - %d\n", tid, gettid());
  pthread_exit(NULL);
}

int main(int argc, char const *argv[]) {
  pthread_t threads[NUM_THREADS];
  int rc;
  long t;

  for (t = 0; t < NUM_THREADS; t++) {
    rc = pthread_create(&threads[t], NULL, printHello, (void *)t);
    if (rc) {
      printf("ERORR; return code from pthread_create() is %d\n", rc);
      exit(EXIT_FAILURE);
    }
  }
  pthread_exit(NULL);
}

출력:

Hello There! thread 0, kthread ID - 10389
Hello There! thread 1, kthread ID - 10390
Hello There! thread 2, kthread ID - 10391
Hello There! thread 3, kthread ID - 10392

thrd_current함수를 사용하여 C에서 스레드 ID 가져 오기

thrd_current는 2011 년 표준 언어 사양에 추가 된 ISO C 스레드 API의 일부입니다.이 API는 POSIX 호환 운영 체제 및 표준 호환 C 컴파일러를 제공하는 모든 플랫폼에 대한 표준 인터페이스를 제공합니다. 따라서이 방법은 C 언어의 스레드와 상호 작용하는 권장 방법입니다. 다음 예제에서는 스레드를 생성하고 종료하기 위해pthread 함수를 사용하지만 프로젝트 작업시 단일 인터페이스 (Pthreads 또는 ISO C)를 선택해야합니다.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>
#include <unistd.h>

#ifndef NUM_THREADS
#define NUM_THREADS 4
#endif

void *printHello(void *threadid) {
  long tid;
  tid = (long)threadid;
  printf("Hello There! thread %ld, pthread ID - %lu\n", tid, thrd_current());
  pthread_exit(NULL);
}

int main(int argc, char const *argv[]) {
  pthread_t threads[NUM_THREADS];
  int rc;
  long t;

  for (t = 0; t < NUM_THREADS; t++) {
    rc = pthread_create(&threads[t], NULL, printHello, (void *)t);
    if (rc) {
      printf("ERORR; return code from pthread_create() is %d\n", rc);
      exit(EXIT_FAILURE);
    }
  }
  pthread_exit(NULL);
}

출력:

Hello There! thread 0, pthread ID - 139727514998528
Hello There! thread 1, pthread ID - 139727506605824
Hello There! thread 2, pthread ID - 139727498213120
Hello There! thread 3, pthread ID - 139727489820416
작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

관련 문장 - C Thread