Search code examples
cmultithreadingpthreadsfork

Does the thread id change after forking a new process?


I know that this fork creates a new process, but what about the thread that was running prior to calling fork, does it also change (because now it is part of a new process "child process" which should have new threads ?)

Compiling and running the following C test confirms that the thread id remains the same:

  pthread_t threadId1, threadId2;

  threadId1 = pthread_self();
  if (fork() == 0)
  {
    threadId2 = pthread_self();
    if (pthread_equal(threadId1,threadId2)) // edited
    {
      printf("we are in the same thread \n");
    }
   else
    {
     printf("we are on different threads \n");
    }

Could someone explain to me why the thread is shared among the parent and child process ?


Solution

  • If you read the pthread_self manual page you will see that

    Thread IDs are guaranteed to be unique only within a process.

    (Emphasis mine)

    That of course means that two very different processes may have threads with the same id.

    If you for some reason want to get the unique kernel id of the thread, use gettid instead.