1

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

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

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]

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

4

2 回答 2

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)
于 2013-09-30T04:56:41.097 回答
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]
于 2013-09-30T04:59:54.217 回答