【问题标题】:Does the thread id change after forking a new process?分叉一个新进程后线程ID会改变吗?
【发布时间】:2017-06-05 05:12:41
【问题描述】:

我知道这个 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");
    }

有人能解释一下为什么线程是在父子进程之间共享的吗?

【问题讨论】:

  • 线程ID是不透明数据,你不应该直接比较它们。而是使用pthread_equal
  • 使用 gettid() 而不是不透明的 pthread_t 结构。
  • 是的,我只是在fork之前和子进程中比较和打印线程id的比较结果。
  • 我不确定,但也许线程绑定到父进程并且它们的 id 仅在其中是唯一的。因此,您可以获得相同的 id。
  • 此外,POSIX 标准声称将线程与 '==' 进行比较是不合适的方式。你必须使用 pthread_equal。

标签: c multithreading pthreads fork


【解决方案1】:

来自 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)

【讨论】:

    【解决方案2】:

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

    线程 ID 只保证在一个进程内是唯一的。

    (强调我的)

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

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

    【讨论】:

    • 我错过了谢谢。
    猜你喜欢
    • 2021-05-31
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    相关资源
    最近更新 更多