0

I am reading a book about unix .It said in linux , thread has different pid . And give the code below to print pid and thread id. I use SUSE and gcc.However, I get the same pid.Can anyone tell me why? Thanks.

#include "pthread.h"
pthread_t ntid;

void printids(const char *s)
{
    pid_t pid;
    pthread_t   tid;
    pid = getpid();
    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)
{
    printids("new thread :");
    return (void *)0;
}
int main()
{
    int err;
    err = pthread_create(&ntid,NULL,thr_fn,strerror(err));
    if(err != 0)
        err_quit("can't create new thread :%s\n",strerror(err));
    printids("main thread :");
    sleep(1);
    exit(0);
}

But,I get this:

main thread : pid = 2945 tid = 3075803392  (0xb7550900)
new thread : pid = 2945 tid = 3075799872  (0xb754fb40)
Lidong Guo
  • 2,817
  • 2
  • 19
  • 31

2 Answers2

2

In Linux threads have the same thread when viewed from user space, from a view space they each have a separate PID.

See also: Linux - Threads and Process

Community
  • 1
  • 1
LostBoy
  • 948
  • 2
  • 9
  • 21
0

Threads are a concept in the same process, they always have the same pid. The pid only changes if you fork a process; in this case, the child process will have a different pid than the parent.

Femaref
  • 60,705
  • 7
  • 138
  • 176