Maison  >  Article  >  développement back-end  >  En langage C, pthread_self() signifie obtenir l'ID du thread actuel

En langage C, pthread_self() signifie obtenir l'ID du thread actuel

WBOY
WBOYavant
2023-09-18 15:21:041219parcourir

En langage C, pthread_self() signifie obtenir lID du thread actuel

Nous examinons ici le rôle de pthread_self() en langage C. La fonction pthread_self() est utilisée pour obtenir l'ID du thread actuel. Cette fonction identifie de manière unique un thread existant. Mais s'il y a plusieurs threads et qu'un thread se termine, l'identifiant peut être réutilisé. Par conséquent, l’identifiant est unique pour tous les threads en cours d’exécution.

Exemple

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* func(void* p) {
   printf("From the function, the thread id = %d</p><p>", pthread_self()); //get current thread id
      pthread_exit(NULL);
   return NULL;
}
main() {
   pthread_t thread; // declare thread
   pthread_create(&thread, NULL, func, NULL);
   printf("From the main function, the thread id = %d</p><p>", thread);
   pthread_join(thread, NULL); //join with main thread
}

Sortie

From the main function, the thread id = 1
From the function, the thread id = 1

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer