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)