Gettid () Get thread ID Test Program

Source: Internet
Author: User

 

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.