织梦CMS - 轻松建站从此开始!

罗索

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

jackyhwei 发布于 2016-12-14 16:40 点击:次 
1、第一种方法 #includestdio.h #includestdlib.h #includeunistd.h #includepthread.h #includesys/syscall.h #definegettid()syscall(__NR_gettid) const int M=3; pthread_thThread[M]; int threadId[M]; void *hello( void *ptr){ int id=*( int *)(ptr); pri
TAG: gettid  pid  获取线程ID  

1、第一种方法

  1. #include "stdio.h" 
  2. #include "stdlib.h" 
  3. #include "unistd.h" 
  4. #include "pthread.h" 
  5. #include <sys/syscall.h> 
  6. #define gettid() syscall(__NR_gettid) 
  7. const int M = 3; 
  8. pthread_t hThread[M]; 
  9. int threadId[M]; 
  10. void *hello(void *ptr) { 
  11.     int id = *(int *)(ptr); 
  12.     printf("Hello! %d/n", id); 
  13.     printf("Thread id:%d/n", gettid()); 
  14.     sleep(1); 
  15.      
  16. void initThreade() { 
  17.     int i; 
  18.     for (i = 0; i < M; ++i) { 
  19.         threadId[i] = i; 
  20.     } 
  21. void MyThreads() { 
  22.     int i; 
  23.     for (i = 0; i < M; i++) { 
  24.         pthread_create(hThread + i, NULL, hello, (void *)(threadId + i)); 
  25.     } 
  26.     for (i = 0; i < M; i++) { 
  27.         pthread_join(hThread[i], NULL); 
  28.     } 
  29. int main(){ 
  30.     initThreade(); 
  31.     MyThreads(); 
  32.     return 0; 
  33.  
  34. 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 <sys/types.h>代替第5、6行

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

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

(zhuliting)
本站文章除注明转载外,均为本站原创或编译欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,同学习共成长。转载请注明:文章转载自:罗索实验室 [http://www.rosoo.net/a/201612/17486.html]
本文出处:CSDN博客 作者:zhuliting
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
相关文章
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
将本文分享到微信
织梦二维码生成器
推荐内容