在python中,线程何时死亡? [英] In python when threads die?

查看:208
本文介绍了在python中,线程何时死亡?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个产生线程的服务. 而且我正在使用的代码中可能会泄漏资源.
我在使用线程的python中有类似的代码

I have a service that spawns threads. And i may have a leak of resources in a code i am using.
I have similar code in python that uses threads

import threading

class Worker(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        # now i am using django orm to make a query
        dataList =Mydata.objects.filter(date__isnull = True )[:chunkSize]
        print '%s - DB worker finished reading %s entrys' % (datetime.now(),len(dataList))

while True:
    myWorker = Worker()
    mwWorker.start()
    while myWorker.isalive():  # wait for worker to finish 
        do_other_work()

还可以吗?
线程在执行完run方法后会死吗?
我会造成资源泄漏吗?

is it ok ?
will the threads die when they finish executing the run method ?
do i cause a leak in resources ?

推荐答案

查看您的上一个问题(您已链接的在注释中),问题是您的文件描述符已用完.

Looking at your previous question (that you linkd in a comment) the problem is that you're running out of file descriptors.

来自官方文档:

文件描述符是与当前进程已打开的文件相对应的小整数.例如,标准输入通常是文件描述符0,标准输出是1,标准错误是2.然后,由进程打开的其他文件将被分配3、4、5,依此类推.名称文件描述符"具有欺骗性;在Unix平台上,套接字和管道也由文件描述符引用.

File descriptors are small integers corresponding to a file that has been opened by the current process. For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2. Further files opened by a process will then be assigned 3, 4, 5, and so forth. The name "file descriptor" is slightly deceptive; on Unix platforms, sockets and pipes are also referenced by file descriptors.

现在我正在猜测,但是可能是您在做类似的事情:

Now I'm guessing, but it could be that you're doing something like:

class Wroker(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        my_file = open('example.txt')
        # operations
        my_file.close()   # without this line!

您需要关闭文件!

您可能正在启动许多线程,并且每个线程都在打开但没有关闭文件,这样一段时间后,您就没有更多的小整数"要分配给打开新文件了.

You're probably starting many threads and each one of them is opening but not closing a file, this way after some time you don't have more "small integers" to assign for opening a new file.

还请注意,在#operations部分中可能会发生任何事情,如果引发异常,除非包裹在try/finally语句中,否则文件不会关闭.

Also note that in the #operations part anything could happen, if an exception is thrown the file will not be close unless wrapped in a try/finally statement.

还有一种更好的处理文件的方法: with声明:

There's a better way for dealing with files: the with statement:

with open('example.txt') as my_file:
     # bunch of operations with the file
# other operations for which you don't need the file

这篇关于在python中,线程何时死亡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆