线程相关函数(2)-pthread_self()获取调用线程ID

时间:2022-10-06 14:55:56

获取调用线程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)\n", 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 != ) {
fprintf(stderr, "can't create thread: %s\n", strerror(err));
exit();
}
printids("main thread: ");
sleep();
return ; }

运行结果:

main thread: pid 4959 tid 9791296 (0x956740)
new thread: pid 4959 tid 1480448 (0x169700)