获取调用线程tid
#include <pthread.h>
pthread_t pthread_self(void);
示例:
#include <pthread.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> void *printids(void *arg) { const char *str = (const char *)arg; pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); printf("%s pid %u tid %u (0x%x) ", str, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid); } int main() { pthread_t tid; int err; err = pthread_create(&tid, NULL, printids, "new thread: "); if (err != 0) { fprintf(stderr, "can't create thread: %s ", strerror(err)); exit(1); } printids("main thread: "); sleep(1); return 0; }
运行结果:
main thread: pid 4959 tid 9791296 (0x956740)
new thread: pid 4959 tid 1480448 (0x169700)