¿cómo obtener el id de hilo de un pthread en un programa linux c?


En el programa linux c, ¿cómo imprimir el id de hilo de un hilo creado por la biblioteca pthread?
por ejemplo: podemos obtener pid de un proceso por getpid()

Author: whoan, 2014-01-13

9 answers

pthread_self() la función dará el id del hilo del hilo actual.

pthread_t pthread_self(void);

La función pthread_self() devuelve el identificador Pthread del hilo invocador. La función pthread_self () NO devuelve el hilo integral del hilo invocador. Debe usar pthread_getthreadid_np() para devolver un identificador integral para el hilo.

NOTA:

pthread_id_np_t   tid;
tid = pthread_getthreadid_np();

Es significativamente más rápido que estas llamadas, pero proporciona el mismo comportamiento.

pthread_id_np_t   tid;
pthread_t         self;
self = pthread_self();
pthread_getunique_np(&self, &tid);
 60
Author: Abhitesh khatri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-22 23:28:33

¿Qué? La persona preguntó por Linux específico, y el equivalente de getpid (). Ni BSD ni Apple. La respuesta es gettid () y devuelve un tipo integral. Tendrás que llamarlo usando syscall (), así:

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

 ....

 pid_t x = syscall(__NR_gettid);

Si bien esto puede no ser portable a sistemas no linux, el threadid es directamente comparable y muy rápido de adquirir. Se puede imprimir (como para los registros) como un entero normal.

 37
Author: Evan Langlois,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-25 18:19:20

Puedes usar pthread_self()

El padre conoce el id del subproceso después de que el pthread_create() se ejecute con éxito, pero al ejecutar el subproceso si queremos acceder al id del subproceso tenemos que usar la función pthread_self().

 9
Author: Jeff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-18 10:14:11

Como se señaló en otras respuestas, pthreads no define una forma independiente de la plataforma para recuperar un ID de hilo integral.

En sistemas Linux, puede obtener el ID de hilo de esta manera:

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

En muchas plataformas basadas en BSD, esta respuesta https://stackoverflow.com/a/21206357/316487 da una forma no portátil.

Sin embargo, si la razón por la que crees que necesitas un ID de subproceso es para saber si estás ejecutando el mismo subproceso o un subproceso diferente a otro subproceso que controlas, es posible que encuentres algunos utilidad en este enfoque

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

Si solo necesitas saber si estás en el hilo principal, hay formas adicionales, documentadas en respuestas a esta pregunta ¿cómo puedo saber si pthread_self es el hilo principal (primero) en el proceso?.

 7
Author: bleater,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:14
pid_t tid = syscall(SYS_gettid);

Linux proporciona dicha llamada al sistema para permitirle obtener el id de un hilo.

 5
Author: Weiqi Gu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-09 20:22:27

Esta sola línea te da pid , cada threadid y spid.

 printf("before calling pthread_create getpid: %d getpthread_self: %lu tid:%lu\n",getpid(), pthread_self(), syscall(SYS_gettid));
 3
Author: nandan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-18 10:08:11

pthread_getthreadid_np no estaba en mi Mac os x. pthread_t es un tipo opaco. No te golpees la cabeza. Simplemente asígnelo a void* y llámelo bueno. Si necesita printf use %p.

 2
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-28 15:13:52

También hay otra forma de obtener id de hilo. Al crear hilos con

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

Llamada a la función; el primer parámetro pthread_t * thread es en realidad un id de hilo (es decir, un int largo sin signo definido en bits/pthreadtypes.h). Además, el último argumento void *arg es el argumento que se pasa a la función void * (*start_routine) para ser enhebrado.

Puede crear una estructura para pasar varios argumentos y enviar un puntero a una estructura.

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
}
 1
Author: Emre Can Kucukoglu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-15 07:20:47

La forma independiente de la plataforma (a partir de c++11) es:

#include <thread>

std::this_thread::get_id();
 1
Author: Oleg Oleg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-09 12:41:30