1. method 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/> 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/> 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
Note:
1. Lines 5th and 6 should not be less; otherwise, an error occurs: Error: 'gettid' was not declared in this scope
2. # include
<Sys/types. h> replaces 5th and 6 rows.
Http://www.kernel.org/doc/man-pages/online/pages/man2/gettid.2.html
3. Add the-lpthread option to the compilation. Otherwise, the "undefined reference to 'pthread _ create'" error will occur.