0

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

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

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()。有人可以帮我解决这个问题吗?谢谢。

4

2 回答 2

3

self.finishedinclass first是 global 值的副本,而finished不是对其的引用,因此它与self.finishedof没有实时关系class second

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

于 2012-04-02T23:20:56.080 回答
1

您可以完全避免同步。使用 3 个线程而不是 2 个线程。

线程 1a '做一些工作' 并终止。线程 1b 从 1a 结束的地方开始,线程 2 独立开始。

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

于 2012-04-02T23:33:14.343 回答