Get thread ID

Source: Internet
Author: User

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

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.