2013-09-30 60 views
1

爲此搜索但找不到任何東西,所以我懷疑它不能完成。Python線程更新Arg

我需要更新參數傳遞給正在運行的線程:

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] 

是否可以更新線程瓦爾/線程之後論點已經開始了嗎?

回答

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) 
+0

感謝shx2&@Alex Brault,最終我用一個全局變量,因爲我用一個線程每個領導,這似乎更新自己的狀態最簡單的方法。 – crankshaft

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]