Python pthread_detach 模拟

标签 python pthreads detach

大家晚上好。我正在使用 Python 2.7 和threading 模块编写多线程程序。这是一个代码示例:

# Importing myFunc function which will be run in the new thread
from src.functions import myFunc
# Importing a threading module
import threading
# Creating and running new thread initiated by our function
# and some parameters.
t = threading.Thread(target=myFunc, args=(1, 2, 3))
t.start()

我知道在 C++(POSIX 线程库)中有一个 pthread_detach()将正在运行的线程置于分离状态的函数。它保证该线程在函数结束后将资源释放回系统。那么,Python 中是否有此类函数的类似物?或者,也许,在Python中根本不需要分离线程,线程占用的资源会在线程函数结束后自动释放?

我试图搜索有关 docs.python.org 的信息和谷歌,但毫无结果。

最佳答案

各位早上好。实际上答案是“根本没有必要在 Python 中分离线程”。这个答案是thereGaiveR同志给我的.您只需要查看 Python 的源代码 (thread_pthread.h):

long
PyThread_start_new_thread(void (*func)(void *), void *arg)
{
...
    status = pthread_create(&th,
#if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED)
                         &attrs,
#else
                         (pthread_attr_t*)NULL,
#endif
                         (void* (*)(void *))func,
                         (void *)arg
                         );

#if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED)
    pthread_attr_destroy(&attrs);
#endif
    if (status != 0)
    return -1;

    pthread_detach(th);
...
}

关于Python pthread_detach 模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14175016/

相关文章:

python - 将特定字符串值映射到 matplotlib.pyplot.imshow() 中的特定颜色

python - 如何通过 python 脚本使用多处理或任何其他模块序列化 msiexec.exe 安装?

python - selenium webdriver python - 如果自定义编写的 python 代码中存在错误,则使 selenium 测试用例失败

c - 使用 clock_gettime() 得到不一致的结果

c - 分离与可连接 POSIX 线程

python - NumPy:获取 3D 数组行和的 argmax 的最快方法

c - 在 pthread 库中禁用 c 断言

c - 输出值与两个 pthread 交错

android - 如何检测 NFC 标签被移除

python - 如何在VS Code中分离Python调试器并让代码完成运行?