bav*_*bav 5 python pthreads detach
各位晚上好。我正在使用 Python 2.7 和线程模块编写多线程程序。这是一个代码示例:
# 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()
Run Code Online (Sandbox Code Playgroud)
我知道在 C++(POSIX 线程库)中有一个pthread_detach()函数,它将正在运行的线程置于分离状态。它保证该线程在函数结束后将资源释放回系统。那么,Python 中有类似的函数吗?或者,也许,Python中根本不需要分离线程,线程占用的资源会在线程函数结束后自动释放?
我尝试在docs.python.org和 Google上搜索信息,但没有结果。
大家早上好。实际上答案是“根本没有必要在Python中分离线程”。这个答案是那里的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);
...
}
Run Code Online (Sandbox Code Playgroud)