刚学多线程,试着将0-99个数字一次输出,为了体现出多线程是否真的比单线程运行速度快,就设置了个每输出一次等待一秒,代码如下:
import time
import threading
def printI(i):
'''输出一次等待一秒'''
print(i)
time.sleep(1)
# 创建1000个线程
threads = []
for i in range(1000):
outings = threading.Thread(target=printI, args=(i,))
threads.append(outings)
# 运行线程
for t in threads:
t.setDaemon(True)
t.start()
代码没有问题,能正常输出并且速度非常快,但问题是输出的时候发现有些格式有问题,没有换行,有问题的输出部分如下:
326
327
328
329
330
331332
333
334
335
336
其中 331 332没有换行 连在一起了,测试了很多遍,总有地方会连在一起,也试过将print(I) 改成print(I,end='') 但是不管用,有没有啥解决办法
import threading import time from threading import RLock class SynchronizedEcho(object): print_lock = RLock() def __init__(self, global_lock=True): if not global_lock: self.print_lock = RLock() def __call__(self, msg): with self.print_lock: print(msg) def printI(i): """输出一次等待一秒""" echo(i) time.sleep(1) # 创建1000个线程 echo = SynchronizedEcho() threads = [] for i in range(1000): outings = threading.Thread(target=printI, args=(i,)) threads.append(outings) # 运行线程 for t in threads: t.setDaemon(True) t.start()
from threading import RLock class SynchronizedEcho(object): print_lock = RLock() def __init__(self, global_lock=True): if not global_lock: self.print_lock = RLock() def __call__(self, msg): with self.print_lock: print(msg)
用 class 输出, 不要 print(i)
稍微有点看不懂 能加一下中文注释吗
仔细找了下相关资料 应该是锁的问题 不会是print的问题 我先去研究一下锁
能讲一下原理吗