我正在尝试运行两个线程,每个线程都传递一个参数进行处理。但是,似乎线程按顺序运行,而不是并行运行。证人:
$ 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!
行会永远继续。为每个线程获得一些处理器时间必须重构什么?
答案 0 :(得分:3)
这是您的问题:在a.join()
b.start()
你想要更像的东西:
a=CallSomebody(call, 'Ghostbusters!')
a.daemon=True
b=CallSomebody(call, 'The Exorcist!')
b.daemon=True
a.start()
b.start()
a.join()
b.join()