2016-01-27 22 views
1

我正在從某個數據流中讀取命令。我陷入了困境,試圖在Python中制定一個可重複使用的非阻塞倒數計時器。所以我開始了一個只有鍵盤輸入和一些基本線程的小程序來計算邏輯。我發現了一些帖子,這篇文章(How to create a trigger with threading.Timer?),這是非常有幫助的。但我需要另一部分的幫助。當值更改時只觸發線程(python)

現在我的邏輯是沿着線:「每次命令的值是1個通話開始」

如何更新我的邏輯是: 「如果命令的值是1個呼叫開始,只要命令的值保持爲1,就不要再次調用start。

所以它比一個正常的if/else更有價值的變化檢測,或者我必須跟蹤某個布爾值。去接近它

#! /usr/bin/env python 

import time 
import threading 
import random 
from random import randint 
import logging 
from sys import argv 


logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] (%(threadName)-10s) %(message)s') 

def countdown(pName,command): 
    print("{0} countdown - command{1} ".format(pName,command)) 
    retry = 0 
    while True: 
     print("{0}:{1}".format(pName,retry)) 
     retry += 1 
     if retry > randint(5,10): 
      break 
     time.sleep(1) 
    print("{0} ended".format(pName)) 

def start(pName,command): 
    print("starting countdown for: ",pName) 
    t = threading.Thread(target=countdown,args=(pName,command)) 
    t.setName(pName) 
    t.setDaemon(True) 
    t.start() 


if __name__ == "__main__": 

    while 1: 
     command = int(input("[1 or 2] >")) 
     if command == 1: 
      start("Salad",command) 

     elif command == 2: 
      start("Bingo",command) 

這是非常暴躁的現在,但它只是第一次嘗試和解決它。

謝謝!

+0

線程在啓動並結束時設置了一個標誌嗎?寫/讀簡單變量是線程安全的,所以只需讓主線程和子線程訪問相同的標誌。或者你可以使用線程鎖作爲你的標誌。 – 101

+0

如果你有一分鐘​​請問,你可以在下面折騰一個答案嗎?當你說旗時,我在想布爾人的真假。哪些會起作用,有時會變得毛茸茸的壽。 –

+1

DJ McMayhem的回答基本上使用內置標誌,甚至更好! – 101

回答

1

你想要的功能isAlive。首先,您必須將線程變量移至主函數,以便main可以調用thread.isAlive()

if __name__ == "__main__": 
    tSalad = threading.Thread() 
    tBingo = threading.Thread() 
    while 1: 
     command = int(input("[1 or 2] >")) 
     if command == 1 and not tSalad.isAlive(): 
      tSalad = threading.Thread(target = countdown, args=("Salad", 1)) 
      start("Salad", tSalad) 

     elif command == 2 and not tBingo.isAlive(): 
      tBingo = threading.Thread(target = countdown, args=("Bingo", 2)) 
      start("Bingo", tBingo) 

然後您修改「開始」功能,將線程的說法:

def start(pName, t): 
    print("starting countdown for: ",pName) 
    t.setName(pName) 
    t.setDaemon(True) 
    t.start() 

這應該爲你做的伎倆。

+0

我知道這是正確的,但我不能有這個主要生活的東西。數據流被拉進主體,所有東西都被髮送到幫助函數。我用.isAlive()嘗試了一些東西,它永遠不會像死一樣開火。 –

+0

@mishap_n好的,你必須有* *主要內容。我想你可以把它保存在一個類中,但是你必須保留這個類的一個對象。然而,你需要看到主題。 – DJMcMayhem

相關問題