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'”錯誤