我是 python 和线程的新手。我试图一次运行多个线程。这是我的基本代码:
import threading
import time
threads = []
print "hello"
class myThread(threading.Thread):
def __init__(self,i):
threading.Thread.__init__(self)
print "i = ",i
for j in range(0,i):
print "j = ",j
time.sleep(5)
for i in range(1,4):
thread = myThread(i)
thread.start()
当 1 个线程正在等待 time.sleep(5)
时,我希望另一个线程启动。简而言之,所有线程都应该并行运行。
最佳答案
你可能对threading.Thread
的子类化有一些误解,首先__init__()
方法大致代表了一个构造函数在 Python 中,基本上每次创建实例时它都会执行,所以在 thread = myThread(i)
执行时,它会阻塞直到 __init__() 结束
。
然后您应该将事件移至 run()
,这样当start()
被调用时,线程就会开始运行。例如:
import threading
import time
threads = []
print "hello"
class myThread(threading.Thread):
def __init__(self, i):
threading.Thread.__init__(self)
self.i = i
def run(self):
print "i = ", self.i
for j in range(0, self.i):
print "j = ",j
time.sleep(5)
for i in range(1,4):
thread = myThread(i)
thread.start()
P.S. 因为GIL
的存在在 CPython 中,如果任务受 CPU 限制,您可能无法充分利用所有处理器。
关于python - 线程在 python 脚本中不并行运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42001643/