我正在尝试运行两个线程,每个线程都有一个传递给它的参数来处理。但是,似乎线程是按顺序运行的,而不是并行运行的。见证:
$ cat threading-stackoverflow.py
import threading
class CallSomebody (threading.Thread):
def __init__(self, target, *args):
self._target = target
self._args = args
threading.Thread.__init__(self)
def run (self):
self._target(*self._args)
def call (who):
while True:
print "Who you gonna call? %s" % (str(who))
a=CallSomebody(call, 'Ghostbusters!')
a.daemon=True
a.start()
a.join()
b=CallSomebody(call, 'The Exorcist!')
b.daemon=True
b.start()
b.join()
$ python threading-stackoverflow.py
Who you gonna call? Ghostbusters!
Who you gonna call? Ghostbusters!
Who you gonna call? Ghostbusters!
Who you gonna call? Ghostbusters!
Who you gonna call? Ghostbusters!
Who you gonna call? Ghostbusters!
Who you gonna call? Ghostbusters!
我希望有一些线路返回Ghostbusters!
,而另一些线路返回The Exorcist!
,但是Ghostbusters!
线路永远持续下去。为了让每个线程获得一些处理器时间,必须重构什么?