linux获取线程ID

半腔热情 提交于 2019-12-03 13:25:05

pthread_self()获取当选线程的ID。
这个ID与pthread_create的第一个参数返回的相同。
但是与ps命令看到的不同,因此只能用于程序内部,用于对线程进行操作。

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

void* fun(void* p)
{
    printf("child thread id=%lu\n",pthread_self());//获取当前线程ID
    //sleep(100);
    return NULL;
}

int main(int argc,char* argv[])
{
    pthread_t tid;
    printf("main thread id=%lu\n",pthread_self());//获取当前线程ID
    pthread_create(&tid,NULL,fun,NULL);
    printf("child's tid=%lu\n",tid);
    sleep(100); //wait child
    return 0;
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!