2

我正在尝试运行两个线程,每个线程都有一个传递给它的参数来处理。但是,似乎线程是按顺序运行的,而不是并行运行的。见证:

$ 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!线路永远持续下去。为了让每个线程获得一些处理器时间,必须重构什么?

4

1 回答 1

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()
于 2012-11-25T20:14:53.007 回答