简体   繁体   中英

In python when threads die?

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()

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 .

From the official doc :

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 need to close your files!

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.

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.

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

Once a thread object is created, its activity must be started by calling the thread's start() method. This invokes the run() method in a separate thread of control. Once the thread's activity is started, the thread is considered 'alive'. It stops being alive when its run() method terminates – either normally, or by raising an unhandled exception. The is_alive() method tests whether the thread is alive.

From python site

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM