Is python's print synchronized?

前端 未结 4 1936
天命终不由人
天命终不由人 2021-01-06 00:34

Is python\'s print synchronized? :)

Between Threads.

4条回答
  •  粉色の甜心
    2021-01-06 01:09

    Kind of workaround... It does not print synchronized, but it is monolithic and thus the threads will not write on top of each other.

    Pros: Does not require locking and thus is faster.

    Cons:

    • It is not synchronized and there is no guarantee the events will be printed in the order happened. As a side effect, if an exception appears, the text of the exception might start before the last few prints are out. They might show up after the exception text or somewhere in the middle of the stack trace.
    • Takes a bit more time and memory to run the loop.
    import threading, time
    
    
    class SomeThread(threading.Thread):
        def __init__(self, name):
            super().__init__()
            self.name = name
            ...
    
        def mono_print(self, *v):
            p = time.strftime("%Y-%m-%d %H:%M:%S") + ' ' + self.name
            for s in v:
                p += ' ' + str(s)
            print(p + '\n', end='', flush=True)
    
        def run(self):
            self.mono_print('thread is running.')
    
            ...
    
            self.mono_print('something', 'them something else')
    
            ...
    
            self.mono_print('processed')

提交回复
热议问题