Python线程更新Arg

时间:2013-09-30 04:48:20

标签: python multithreading

搜索了这个但找不到任何东西,所以我怀疑它无法完成。

我需要更新正在运行的线程的参数:

def doLeds(*leds):
    onoff = 0
    while 1:
        onoff=not onoff
        for led in leds:
            wpi.digitalWrite(led,onoff)
            time.sleep(0.025)


def thread():
    from threading import Thread
    leds = Thread(target=doLeds, args=([17,22,10,9,11]))
    leds.start()
    print(leds)
    time.sleep(5)
    leds['args']=[10,9,11]

在线程启动后是否可以更新线程变量/参数?

2 个答案:

答案 0 :(得分:0)

不确定。如果你继承Thread,这很容易。然后,您可以直接分配其属性。

class LedThread(Thread):
    def __init__(self, args):
        Thread.__init__(self)
        self.args = args
    def run(self):
        self.doLeds()
    def doLeds(self):
        onoff = 0
        while 1:
            onoff=not onoff
            for led in self.args:
                wpi.digitalWrite(led,onoff)
                time.sleep(0.025)

t = LedThread([17,22,10,9,11])
t.start()
time.sleep(10)
t.args = [10,9,11]
time.sleep(10)

答案 1 :(得分:0)

如果使用带可调用的基本线程,则无法更改参数。那是因为在线程启动之后,它会将参数传递给目标,然后忘记它们。

您可以做的是创建一个扩展threading.Thread的类。然后,您可以使用您过去作为参数传递的字段。例如:

from threading import Thread

class LedThread(Thread):
    def __init__(self, leds):
        Thread.__init__(self)
        self.leds = leds

    def run(self):
        onoff = 0
        while 1:
            onoff=not onoff
            for led in leds:
                wpi.digitalWrite(led,onoff)
                time.sleep(0.025)

def thread():
    leds = LedThread([17,22,10,9,11])
    leds.start()
    print(leds)
    time.sleep(5)
    leds.leds=[10,9,11]