獲取線程ID


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;
}

 

C++11 thread獲取線程ID

std::cout << "worker thread ID:" << std::this_thread::get_id() << std::endl;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM