gettid()获取线程ID测试程序

 

1、第一种方法

#include "stdio.h" #include "stdlib.h" #include "unistd.h" #include "pthread.h" #include #define gettid() syscall(__NR_gettid) const int M = 3; pthread_t hThread[M]; int threadId[M]; void *hello(void *ptr) { int id = *(int *)(ptr); printf("Hello! %d/n", id); printf("Thread id:%d/n", gettid()); sleep(1); } void initThreade() { int i; for (i = 0; i < M; ++i) { threadId[i] = i; } } void MyThreads() { int i; for (i = 0; i < M; i++) { pthread_create(hThread + i, NULL, hello, (void *)(threadId + i)); } for (i = 0; i < M; i++) { pthread_join(hThread[i], NULL); } } int main(){ initThreade(); MyThreads(); return 0; } g++ hello.c -o hello -lpthread
[root@zhuliting ft]# g++ hello.c -o hello -lpthread

[root@zhuliting ft]# ./hello
Hello! 0
Thread id:17783
Hello! 1
Thread id:17784
Hello! 2
Thread id:17785

 

 

注意:

1、第5、6行不能少,否则会出现错误:error: ‘gettid’ was not declared in this scope 

2、#include 代替第5、6行

http://www.kernel.org/doc/man-pages/online/pages/man2/gettid.2.html 

3、编译加上-lpthread选项,不然会出现“undefined reference to `pthread_create'”错误

你可能感兴趣的:(Linux,Linux多线程)