Python多线程处理:需要使用条件变量同步2个线程吗

2024-09-28 05:22:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我只知道多线程的基本概念,我目前遇到了一个需要帮助的情况。在

我有两个任务要完成,这两个任务都应该持续执行。问题是第二个任务应该在第一个线程先完成一些任务之后才开始。现在,这两个线程类大致如下所示:

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()如何,程序仍然随机执行。有人能帮我解决这个问题吗?谢谢。在


Tags: runselffalseinitdef线程dothread
2条回答

class first中的self.finished是全局finished值的副本,而不是对它的引用,因此它与class secondself.finished没有实时关系。在

您可能应该创建一个全局Queue对象(它是为与threading模块一起使用而设计的)。让这两个类都引用队列,并让第一个线程向队列写入一个执行信号,第二个线程阻塞,直到它读取到执行。在

您可以完全避免同步。使用3个螺纹代替2个螺纹。在

线程1a“执行某些任务”并终止。 线程1b从1a结束处开始,并且 线程2独立启动。在

(另外,我想您知道不能与Python线程有效地共享CPU;这些线程只适用于并行等待的I/O。当您需要CPU限制的并行化时,可以使用multiprocessing。)

相关问题 更多 >

    热门问题