Python: How can I stop Threading/Multiprocessing from using 100% of my CPU?

Viewed 1370

I have code that reads data from 7 devices every second for an infinite amount of time. Each loop, a thread is created which starts 7 processes. After each process is done the program waits 1 second and starts again. Here is a snippet the code:

def all_thread(): #function that handels the threading
    thread = threading.Thread(target=all_process) #prepares a thread for the devices
    thread.start() #starts a thread for the devices

def all_process(): #function that prepares and runs processes
    processes = [] #empty list for the processes to be stored
    while len(gas_list) > 0: #this gaslist holds the connection information for my devices
        for sen in gas_list: #for each sen(sensor) in the gas list
            proc = multiprocessing.Process(target=main_reader, args=(sen, q)) #declaring a process variable that sends the gas object, value and queue information to reading function
            processes.append(proc) #adding the process to the processes list
            proc.start() #start the process
        for sen in processes: #for each sensor in the processes list
            sen.join() #wait for all the processes to complete before starting again
        time.sleep(1) #wait one second

However, this uses 100% of my CPU. Is this by design of threading and multiprocessing or just bad coding? Is there a way I can limit the CPU usage? Thanks!

Update:

The comments were mentioning the main_reader() function so I will put it into the question. All it does is read each device, takes all the data and appends it to a list. Then the list is put into a queue to be displayed in the tkinter GUI.

def main_reader(data, q): #this function reads the device which takes less than a second
    output_list = get_registry(data) #this function takes the device information, reads the registry and returns a list of data
    q.put(output_list) #put the output list into the queue
1 Answers
Related