Use of threading.Thread.join()

后端 未结 3 1593
迷失自我
迷失自我 2020-12-08 07:22

I am new to multithreading in python and trying to learn multithreading using threading module. I have made a very simple program of multi threading and i am having trouble

3条回答
  •  借酒劲吻你
    2020-12-08 08:22

    A call to thread1.join() blocks the thread in which you're making the call, until thread1 is finished. It's like wait_until_finished(thread1).

    For example:

    import time
    
    def printer():
        for _ in range(3):
            time.sleep(1.0)
            print "hello"
    
    thread = Thread(target=printer)
    thread.start()
    thread.join()
    print "goodbye"
    

    prints

    hello
    hello
    hello
    goodbye
    

    —without the .join() call, goodbye would come first and then 3 * hello.

    Also, note that threads in Python do not provide any additional performance (in terms of CPU processing power) because of a thing called the Global Interpreter Lock, so while they are useful for spawning off potentially blocking (e.g. IO, network) and time consuming tasks (e.g. number crunching) to keep the main thread free for other tasks, they do not allow you to leverage multiple cores or CPUs; for that, look at multiprocessing which uses subprocesses but exposes an API equivalent to that of threading.

    PLUG: ...and it is also for the above reason that, if you're interested in concurrency, you might also want to look into a fine library called Gevent, which essentially just makes threading much easier to use, much faster (when you have many concurrent activities) and less prone to concurrency related bugs, while allowing you to keep coding the same way as with "real" threads. Also Twisted, Eventlet, Tornado and many others, are either equivalent or comparable. Furthermore, in any case, I'd strongly suggest reading these classics:

    • Generator Tricks for Systems Programmers
    • A Curious Course on Coroutines and Concurrency

提交回复
热议问题