我有一个简单的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()
最佳答案
在Python中,线程构造函数应该总是使用关键字参数来调用。因此,为了让您的程序正常工作,您需要 target 关键字来指向线程需要运行的函数。
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(target=from_1).start()
threading.Thread(target=from_2).start()
关于python - 我不能在python中启动两个并行线程吗,每个线程都有一个forerver循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63790078/