Advanced Programming in UNIX environment: print the thread ID

Source: Internet
Author: User

The book "Advanced Programming in UNIX environments" comes with many small and exquisiteProgramWhen I read this bookCodeI have rewritten it according to my own understanding (most of it is on the copybook) and deepened my understanding (it is too difficult to read a book, haha ). This example is successfully tested on ubuntu10.04.


Program Introduction: The following program creates a thread and prints the process ID, the ID of the new thread, and the ID of the thread of the initial thread.


// Apue Program 11-1: create a sub-thread and print its thread ID # include <unistd. h> # include <stdio. h> # include <stdlib. h> # include <pthread. h> pthread_t ntid; void printfids (const char * s) {// print the process ID and thread idpid_t pid = getpid (); pthread_t tid = pthread_self (); printf ("% s PID % u TID % u (0x % x) \ n", S, (unsigned INT) PID, (unsigned INT) tid, (unsigned INT) TID);} void * thr_fn (void * Arg) {printfids ("New thread:"); Return (void *) 0;} int main (void) {pthread_create (& ntid, null, thr_fn, null); printfids ("main thread:"); // sleep the main thread for 1 second, this is an exercise for ensuring that sub-threads can run sleep (1); Return 0 ;}

Running example (in red ):

qch @ Ubuntu :~ /Code $ GCC
temp. c-lpthread-O temp
qch @ Ubuntu :~ /Code $ . /temp
main thread: PID 4153 TID 3078440640 (0xb77d46c0)
New thread: PID 4153 TID 3078437744 (0xb77d3b70)

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.