简体   繁体   中英

Python & Tkinter: Multiprocessing from multiple classes

I have a Tkinter program that has eight classes. Six of those classes are pages, so each page of the GUI has its own class. I need to setup multiprocessing across the classes and I need the processes to join at the same time. Here is an example of a class and my multiprocessing setup:

class Page1(Page):
    def __init__(self, *args, **kwargs):
       Page.__init__(self, *args, **kwargs)
       #setting up gas varible to read from
       self.gas = minimalmodbus.Instrument("COM3", 1)
       self.gas.serial.baudrate = 9600
       self.gas.serial.bytesize = 8
       self.gas.serial.parity = serial.PARITY_NONE
       self.gas.serial.stopbits = 1
       self.gas.serial.timeout = 0.25
       self.gas.mode = minimalmodbus.MODE_RTU

       self.timer_button = tk.Button(self, text='Start', command=self.toggle)
       self.timer_button.pack(side="top")

    def toggle(self):
            all_thread(self.gas)

def all_thread(a_gas):
    thread = threading.Thread(target=all_process(a_gas))

def all_process(a_gas):
    gas_list = []
    gas_list.append(a_gas)
    processes = []
    while len(gas_list) > 0:
        for sen in gas_list:
            proc = Process(target=main_reader(sen))
            processes.append(proc)
            proc.start()
        for sen in processes:
            sen.join()
        time.sleep(1)

def main_reader(gas_num):
    read = gas_num.read_registers(0,42)
    print(read)

This works, I get all the output I want in the console. However, my GUI freezes and crashes when I press the timer_button . Am I on the right track/what am I doing wrong?

This code:

thread = threading.Thread(target=all_process(a_gas))

... is exactly the same as this code:

result = all_process(a_gas)
thread = threading.Thread(target=result)

You aren't running the command in a thread, which is why your program freezes. You must assign a callable to the target. If you need to pass arguments, use args :

thread = threading.Thread(target=all_process, args=(a_gas,))

This is all documented in the python documentation. See https://docs.python.org/2/library/threading.html#threading.Thread

You have the same problem when you start a process.

This:

proc = Process(target=main_reader(sen))

... is exactly the same as this:

result = main_reader(sen)
proc = Process(target=result)

So, just like you aren't using threads, you also aren't using processes. Again, this is all documented: https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM