我只知道多线程的基本概念,我目前遇到了一个需要帮助的情况。在
我有两个任务要完成,这两个任务都应该持续执行。问题是第二个任务应该在第一个线程先完成一些任务之后才开始。现在,这两个线程类大致如下所示:
finished = False # shared flag
class first(threading.Thread):
def __init__(self, cond, finished):
threading.Thread.__init__(self)
self.cond = cond
self.finished = finished
def run(self):
self.cond.aquire()
do_something()
self.finished = True #change the flag
self.cond.notify()
self.cond.release()
do_something_else()
class second(threading.Thread):
def __init__(self, cond, finished):
threading.Thread.__init__(self)
self.cond = cond
self.finished = finished
def run(self):
self.cond.aquire()
while self.finished == False:
self.cond.wait()
self.cond.release()
do_something()
然而,事实是,无论wait()和notify()如何,程序仍然随机执行。有人能帮我解决这个问题吗?谢谢。在
class first
中的self.finished
是全局finished
值的副本,而不是对它的引用,因此它与class second
的self.finished
没有实时关系。在您可能应该创建一个全局
Queue
对象(它是为与threading
模块一起使用而设计的)。让这两个类都引用队列,并让第一个线程向队列写入一个执行信号,第二个线程阻塞,直到它读取到执行。在您可以完全避免同步。使用3个螺纹代替2个螺纹。在
线程1a“执行某些任务”并终止。 线程1b从1a结束处开始,并且 线程2独立启动。在
(另外,我想您知道不能与Python线程有效地共享CPU;这些线程只适用于并行等待的I/O。当您需要CPU限制的并行化时,可以使用multiprocessing。)
相关问题 更多 >
编程相关推荐