【发布时间】:2020-12-26 14:43:26
【问题描述】:
我有一个简单的 Python3 代码,我想同时启动这两个函数,但只运行了“from_1”。 问题:没有 .sleep() 函数我如何管理两个线程,Python 有什么要管理的吗?
import threading
def from_1():
i = 1
while True:
print("Thread 1 {}".format(i))
f = open('face1.jpeg','rb')
img = f.read()
f = open('face1_w.jpeg','wb')
f.write(img)
f.close()
i += 1
def from_2():
i = 1
while True:
print("Thread 2 {}".format(i))
f = open('face2.jpeg','rb')
img = f.read()
f = open('face2_w.jpeg','wb')
f.write(img)
f.close()
i-= 1
if __name__ == '__main__':
jobs = []
threading.Thread(from_1()).start()
threading.Thread(from_2()).start()
【问题讨论】:
-
在每个线程中都有一个
sleep是很常见的,这样您就可以准确地安排一个线程应该让其他线程控制的时间。即使您不这样做,Python 也会切换线程,但建议您这样做。无论如何,您的错误是您甚至在构造线程之前就调用了from_1()。 -
IDK,但您应该关闭代码读取的文件。如图所示,它只关闭您正在编写的文件。考虑使用
with语句来关闭文件。 stackoverflow.com/a/8011836/801894
标签: python multithreading