線程相關函數(2)-pthread_self()獲取調用線程ID


獲取調用線程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 != 0) {
        fprintf(stderr, "can't create thread: %s\n", 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)

 


免責聲明!

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



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