让多个线程根据全局变量执行操作

Having multiple threads perform actions based on a global variable

我试图让一个线程更改全局变量,然后让其他线程检查该全局变量,如果它发生更改,则执行一些操作。我已经通读了线程 python 文档,但这对我来说都是全新的,我不确定我正在尝试做的事情的最佳选择是什么,或者我正在做的事情是否愚蠢并且有更好的方法?此代码不会像我期望的那样改变彩色打印语句。 (此外,对于我在实际项目中使用的其他一些模块,此代码必须在 python 2.x 中。)...也许我应该使用队列对象。

import random
import sys
import threading
import time

# Globals
output = None

class Green(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        while True:
            if output == 'green':
                print 'green'
                time.sleep(1)


class Red(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        while True:
            if output == 'red':
                print 'red'
                time.sleep(1)


class Color_Randomizer(threading.Thread):
    def __init__(self):
        global output
        threading.Thread.__init__(self)

    def run(self):
        while True:
            colors = ['red', 'green']
            output = random.choice(colors)
            time.sleep(1)


def main():

    green = Green()
    red = Red()
    color_randomizer = Color_Randomizer()

    print 'Starting green'
    green.start()
    print 'Starting red'
    red.start()
    print 'Starting color randomizer'
    color_randomizer.start()

if __name__ == "__main__":
    main()

本例中的代码非常简单,因此很多隐藏的问题在这里都看不到。第一个是实际看到的:总体而言,使用全局变量并不是最好的方法。

随着代码变得越来越复杂,会出现更多问题。第一个是,如果你使用更复杂的全局结构,你将不得不处理它的修改的原子性。

与线程通信 是有意义的 - 使用队列是一种可能性。您将发送当前颜色和了解如何处理该颜色响应的线程。这与您处理并行通信(或在 Python 的情况下并发)环境的方式相同。

将颜色的变化想象成一个事件,将您的线程池想象成事件处理程序。这很好地说明了流程:发出事件,候选人做出回应。现在,即使您添加了更多事件源(颜色生成器),并发访问单个变量也不会有问题。另一方面,保持顺序需要一些同步机制。

你永远不会改变全局变量output.ColorRandomizer.run中的变量output是一个隐藏全局变量的局部变量。

在 Color_Randomizer 的 run 函数顶部插入行 global output

删除 Color_Randomizer() 中的 return output 语句。您在下一行中的 time.sleep 呼叫无法接通。此外,从线程返回值没有意义,因为没有办法使用它。