When will the main thread come out in python

I read The Python Standard Library by Exampleand be embarrassed when I came to page 509.

Up to this point, the sample programs implicitly waited for the exit, until all threads had completed their work. Programs sometimes spawn a thread as a daemon that starts without blocking the main program from exiting.

but after running some codes, I get the opposite result. The code looks like this:

    #!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""Creating and waiting for a thread.
"""
#end_pymotw_header

import threading
import time

def worker():
    """thread worker function"""
    print 'Worker'
    # time.sleep(10000)
    return

threads = []
for i in range(5):
    t = threading.Thread(target=worker)
    threads.append(t)
    t.start()

print "main Exit"

and someday the result:

Worker
Worker
WorkerWorker

main Exit
Worker

So, I want to ask, when will the main thread come out in python after it starts multiple threads?

+4
source share
5 answers

The main thread will exit when it finishes executing all the code in a script that does not run in a separate thread.

t.start() , , , script, .

, , .

, , , join . join , join, , .

for i in range(5):
    threads[i].join()
print "main Exit"

@codesparkle, Pythonic , .

for thread in threads:
    thread.join()
print "main Exit"
+9

:

Python ,

, , , . " " , . , - . , , , .

, , , - . , - - , " ", ( , - ) . ​​

+5

, . . , , . 5 .

0

, Main , main Exit, . :

import threading
import time

def worker():
    """thread worker function"""
    print 'Worker'
    time.sleep(1)
    print 'Done'
    return


class Exiter(object):
    def __init__(self):
        self.a = 5.0
        print 'I am alive'
    def __del__(self):
        print 'I am dying'

exiter = Exiter()

threads = []
for i in range(5):
    t = threading.Thread(target=worker)
    threads.append(t)
    t.start()

print "main Exit"

, " ", . , , , Python , .

, , , , . I am dying , .

0

, :

    class ThreadA(Thread):
        def __init__(self, mt):
            Thread.__init__(self)
            self.mt = mt

        def run(self):
            print 'T1: sleeping...'
            time.sleep(4)
            print 'current thread is ', self.isAlive()
            print 'main thread is ', self.mt.isAlive()
            print 'T1: raising...'

if __name__ == '__main__':
    mt = threading.currentThread()
    ta = ThreadA(mt)
    ta.start()
    logging.debug('main end')
< →   T1: ...

(MainThread) main end

True

- False

T1: ...

, ?

0

Source: https://habr.com/ru/post/1538010/


All Articles