Why a script that uses threads prints extra lines occasionally?

后端 未结 2 879
遇见更好的自我
遇见更好的自我 2020-12-10 07:09

If print s is replaced by print >>sys.stderr, s then the effect vanishes.

import random, sys, time
import threading

lock = t         


        
2条回答
  •  时光取名叫无心
    2020-12-10 07:50

    Take a look at this stackoverflow thread: How do I get a thread safe print in Python 2.6?. Apparently, printing to sout is not thread-safe.

    If you turn on verbose threading, you can see this better:

    threading.Thread(target=echo, args=(c,), verbose=True).start()
    

    I get output like this:

    MainThread: .start(): starting thread
    Thread-1: .__bootstrap(): thread started
    MainThread: .start(): starting thread
    Thread-2: .__bootstrap(): thread started
    MainThread: .start(): starting thread
    Thread-3: .__bootstrap(): thread started
    MainThread: .join(): waiting until thread stops
    a
    b
    Thread-1: .__bootstrap(): normal return
    Thread-2: .__bootstrap(): normal return
    MainThread: .join(): thread stopped
    MainThread: .join(): waiting until thread stops
    Thread-3: .__bootstrap(): normal return
    MainThread: .join(): thread stopped
    c
    

    You can see that thread 3 is shown as finishing before printing the 'c' character. This clearly cannot be the case, so this leads me to assume that printing to the console is not thread-safe.

    This, however, does not explain why printing to sys.stderr appears to work correctly.

提交回复
热议问题