gpt4 book ai didi

c - pthread_create 是否启动创建的线程?

转载 作者:IT王子 更新时间:2023-10-29 00:54:40 29 4
gpt4 key购买 nike

"pthread_create" 函数是启动线程(开始执行它的函数),还是只是创建它并让它等待合适的时机启动?

最佳答案

pthread_create 创建线程(通过内部使用 clone 系统调用),并返回 tid(线程 ID,如 pid)。所以,在pthread_create 返回的时候,新的线程至少被创建了。但无法保证何时开始。

来自男人: http://man7.org/linux/man-pages/man3/pthread_create.3.html

Unless real-time scheduling policies are being employed, after a call to pthread_create(), it is indeterminate which thread—the caller or the new thread—will next execute.

POSIX在pthread_create的信息描述中有类似的注释http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_create.html

There is no requirement on the implementation that the ID of the created thread be available before the newly created thread starts executing.

还有很长的“基本原理”为什么 pthread_create 是单步过程,没有单独的线程创建和 start_execution(因为它在良好的旧 Java 时代):

A suggested alternative to pthread_create() would be to define two separate operations: create and start. Some applications would find such behavior more natural. Ada, in particular, separates the "creation" of a task from its "activation".

Splitting the operation was rejected by the standard developers for many reasons:

  • The number of calls required to start a thread would increase from one to two and thus place an additional burden on applications that do not require the additional synchronization. The second call, however, could be avoided by the additional complication of a start-up state attribute.

  • An extra state would be introduced: "created but not started". This would require the standard to specify the behavior of the thread operations when the target has not yet started executing.

  • For those applications that require such behavior, it is possible to simulate the two separate steps with the facilities that are currently provided. The start_routine() can synchronize by waiting on a condition variable that is signaled by the start operation.

您可以使用RT调度;或者只是在创建的线程中添加一些同步以获取有关其执行的准确信息。在某些情况下,使用 pthread_setaffinity_np 手动将线程绑定(bind)到特定的 CPU 内核也很有用。

关于c - pthread_create 是否启动创建的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23051676/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com