1#include <pthread.h>2#include <unistd.h>3#include <stdio.h>4#include <stdlib.h>5#include <string.h>6 pthread_t Ntid;
7 /**8 * Function: Print process ID, print thread ID. 9 * Note that the-lpthread parameter is added at compile time to invoke the static link library. Because Pthread is not the default library for Linux systemsTen * gcc pthread.c-lpthread-o pthread One */ A voidPrintids (Const Char*s) - { - pid_t pid; the pthread_t tid; - //gets the current process ID -PID =getpid (); - //gets the current thread ID
+Tid =pthread_self ();//Get the ID of the thread itself - //prints the current process ID, prints the current thread ID +printf"%s pid%u strerrortid%u (0x%x) \ n", S, A(unsignedint) PID, (unsignedint) Tid, (unsignedint) tid); at } - - void*TH_FN (void*Arg) - { - Printids (ARG); - returnNULL; in } - to intMainvoid) + { - the intErr =0;
1 /*2 pthread_create function3 4 Thread creation function5 6 header files and function prototypes7 #include <pthread.h>8 int pthred_creat (pthread_t *restrict tidp,const pthread_attr_t *restric attr, void * (*START_RTN) (void *), void *restr ICT arg);9 Ten Parameters One The first parameter is a pointer to the thread identifier. A The second parameter is used to set the thread properties. - The third parameter is the starting address of the thread's running function. - the last parameter is the parameter that runs the function. the - */
*Err = Pthread_create (&ntid, NULL, TH_FN,"New Thread:"); $ if(Err! =0) {Panax Notoginsengfprintf (stderr,"errno:%s", Strerror (err)); -Exit1); the } +Printids ("Main thread:"); A //to not let the process end prematurely than the thread, the delay is 1 seconds to execute theSleep1); + return 0; -}
1 Program Run Results 2 main thread: 37553814000384 (0xe3550700)3New thread: 37553805734656 (0xe2d6e700)
Get thread ID