大家晚上好。我正在使用 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 中分离线程”。这个答案是there的GaiveR同志给我的.您只需要查看 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/