Is python's print synchronized?

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

Is python\'s print synchronized? :)

Between Threads.

4条回答
  •  感情败类
    2021-01-06 01:12

    The answer is no, threads can interrupt each other. However, you can use locks to avoid that.

    lock's prevent threads from interrupting each other on global things (specifically here the output screen) when a thread want's to use global thing with a lock, it first checks if the lock is unlocked, if not it waits until it is, after that it locks the lock, do the stuff it want's to do with the global thing, and finally release the lock.

    However, don't just use flag variables and if checks to implement this, the threads can switch between the if statement and the locking. Python implements a lock class, if I remember correctly its threading.lock.

    Also, note that you can run into a deadlock or a livelock if you don't use locks correctly. I don't have much time now so I can't really explain all that here, but you can google that for more info, I'll also check if I can share presentations from my last year's course in university, they explain that pretty good in there.

提交回复
热议问题