如何重启python多线程

时间:2017-11-23 11:06:41

标签: python multithreading user-interface tkinter

我正在尝试为我的系统设计一个控制接口,通过串行链接发送和接收一些数据。我对GUI设计的搜索让我理解了“多线程”问题,下面的代码显示了我到达的最新位置。

这表示我在示例GUI上看到的类似部分(例如try,run)。我计划将其转换为GUI,一旦我理解它是如何工作的。

所以问题出在我启动后,停止下面的代码我再也无法重启了。因为,据我所知,多线程功能只有一个周期:启动,停止和退出。我的意思是它在停止后不接受启动命令。

我的问题是如何让这段代码在停止后接受启动?

祝福

import threading, random, time    
class process(threading.Thread):        
    def __init__(self):
        threading.Thread.__init__(self)          
    def run(self):          
        self.leave  = 0 
        print("\n it's running ...\n\n")            
        while self.leave != 1:  
            print "Done!"
            time.sleep(1)   

operate = process()    

while True:
    inputt = input("   START : 1 \n   STOP\t : 0 \n   QUIT\t : 2 \n")       
    try:
        if int(inputt) == 1:
            operate.start()             
        elif int(inputt) == 0:
            operate.leave = 1               
        elif int(inputt) == 2:
            break

    except:
        print(" Wrong input, try egain...\n")

1 个答案:

答案 0 :(得分:0)

process循环

中创建while True
    if int(inputt) == 1:
        operate = process()    
        operate.start()             

它应该有用。

...但是您的代码可能需要进行其他更改以使其更安全 - 您必须在尝试停止之前检查进程是否存在。您可以使用operate = None来控制它。

import threading
import random
import time    


class Process(threading.Thread):        

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

    def run(self):          
        self.leave = False
        print("\n it's running ...\n\n")            
        while self.leave == False:  
            print("Done!")
            time.sleep(1)   

operate = None

while True:
    inputt = input("   START : 1 \n   STOP\t : 0 \n   QUIT\t : 2 \n")       
    try:
        if int(inputt) == 1:
            if operate is None:
                operate = Process()    
                operate.start()             
        elif int(inputt) == 0:
            if operate is not None:
                operate.leave = True
                operate.join() # wait on process end
                operate = None
        elif int(inputt) == 2:
            if operate is not None:
                operate.leave = True
                operate.join() # wait on process end
            break
    except:
        print(" Wrong input, try egain...\n")

当您设置run()但继续运行thead时,其他方法不会离开leave = True。你需要两个循环。

 def run(self):          
    self.leave = False
    self.stoped = False
    print("\n it's running ...\n\n")            
    while self.leave == False:  
        while self.stoped == False:
             print("Done!")
        time.sleep(1)