gettid()擷取線程ID測試程式

來源:互聯網
上載者:User

 

1、第一種方法

#include "stdio.h"<br />#include "stdlib.h"<br />#include "unistd.h"<br />#include "pthread.h"<br />#include <sys/syscall.h><br />#define gettid() syscall(__NR_gettid)<br />const int M = 3;<br />pthread_t hThread[M];<br />int threadId[M];<br />void *hello(void *ptr) {<br />int id = *(int *)(ptr);<br />printf("Hello! %d/n", id);<br />printf("Thread id:%d/n", gettid());<br />sleep(1);</p><p>}<br />void initThreade() {<br />int i;<br />for (i = 0; i < M; ++i) {<br />threadId[i] = i;<br />}<br />}<br />void MyThreads() {<br />int i;<br />for (i = 0; i < M; i++) {<br />pthread_create(hThread + i, NULL, hello, (void *)(threadId + i));<br />}<br />for (i = 0; i < M; i++) {<br />pthread_join(hThread[i], NULL);<br />}<br />}<br />int main(){<br />initThreade();<br />MyThreads();<br />return 0;<br />}</p><p>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'”錯誤

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.