在分配新流程后,线程ID是否会发生变化?

时间:2017-01-20 09:10:23

标签: c multithreading pthreads fork

我知道这个fork创建了一个新进程,但是在调用fork之前运行的线程怎么样呢,它也会改变(因为现在它是新进程的一部分"子进程"应该有新的线程?)

编译并运行以下C测试确认线程ID保持不变:

  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");
    }

有人可以向我解释为什么在父和子进程之间共享线程吗?

2 个答案:

答案 0 :(得分:4)

如果您阅读the pthread_self manual page,您会看到

  

保证线程ID仅在流程中唯一

(强调我的)

这当然意味着两个非常不同的进程可能具有相同id的线程。

如果由于某种原因想要获取线程的唯一内核ID,请改用getid

答案 1 :(得分:3)

来自pthread_self的手册页

   Thread IDs are guaranteed to be unique only within a process.  A
   thread ID may be reused after a terminated thread has been joined, or
   a detached thread has terminated.

   The thread ID returned by pthread_self() is not the same thing as the
   kernel thread ID returned by a call to gettid(2).

由于fork有效地复制了一个进程,包括它对内核对象的句柄,因此结果并不意外。 (内核在进行对象查找时使用句柄值和pid)

相关问题