python多线程控制暂停_Python:如何使用100%的CPU停止线程/多处理?

我的代码每秒钟从7个设备读取数据,无限时间.每个循环,创建一个启动7个进程的线程.每个过程完成后,程序等待1秒钟再次启动.这是代码片段:

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

但是,这使用了我100%的CPU.这是通过线程和多处理的设计还是只是糟糕的编码?有没有办法限制CPU使用率?谢谢!

更新:

评论提到了main_reader()函数,所以我会把它放到问题中.它所做的就是读取每个设备,获取所有数据并将其附加到列表中.然后将列表放入队列以显示在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

解决方法:

正如您在注释中所述,您的main_reader只需要几分之一秒即可运行,这意味着进程创建开销可能会导致您的问题.

以下是multiprocessing.Pool的示例.这将创建一个工作池并将您的任务提交给他们.进程只启动一次,如果这是一个无限循环,则永远不会关闭或连接.如果要关闭池,可以通过加入和关闭池来实现(请参阅相关文档).

from multiprocessing import Pool, Manager

from time import sleep

import threading

from random import random

gas_list = [1,2,3,4,5,6,7,8,9,10]

def main_reader(sen, rqu):

output = "%d/%f" % (sen, random())

rqu.put(output)

def all_processes(rq):

p = Pool(len(gas_list) + 1)

while True:

for sen in gas_list:

p.apply_async(main_reader, args=(sen, rq))

sleep(1)

m = Manager()

q = m.Queue()

t = threading.Thread(target=all_processes, args=(q,))

t.daemon = True

t.start()

while True:

r = q.get()

print r

如果这没有帮助,你需要开始深入挖掘.我首先会将无限循环中的睡眠时间增加到10秒甚至更长.这将允许您监视程序的行为.如果CPU暂停一段时间然后稳定下来10秒左右,您就会知道问题出在您的main_reader中.如果它仍然是100%,你的问题必须在其他地方.

您的问题可能根本不在您的程序的这一部分吗?你似乎在一个线程中启动了这一切,这表明你的主程序正在做其他事情.这可能是其他高峰CPU的东西吗?

标签:python,multithreading,multiprocessing

来源: https://codeday.me/bug/20190701/1349318.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值