美文网首页
Python 多进程队列处理耗时操作的模版

Python 多进程队列处理耗时操作的模版

作者: 牛奶芝麻 | 来源:发表于2020-11-24 16:16 被阅读0次
问题:

requests.get(image_url).content 可以读取一个 image_url 中的内容,但是如果有多个 image_url,读取速度会比较慢。因此,可以利用多进程队列去处理。模板如下:

import requests
import json
import traceback
import multiprocessing as mp

queue_before_downloader = mp.Queue()  # 队列保存处理之前的数据
queue_after_downloader = mp.Queue()  # 队列保存处理之后的数据
num_workers = 10

def chunk(chunk_size=64, num_workers=10):  # chunk 一个 batch 的结果
  global args
  count_none = 0
  global queue_after_downloader
  ret = []
  while True:
    item = queue_after_downloader.get()
    if item is None:
      count_none += 1
      if count_none == num_workers:
        if len(ret) != 0:
          print('latest chunk')  # 最后一次chunk
          yield ret
        return
      continue
    ret.append(item)
    if len(ret) == chunk_size:
      yield ret
      ret = []


def process_sample():  # 一次解析一个url数据,耗时的函数
  global queue_before_downloader
  global queue_after_downloader

  while True:
    info = queue_before_downloader.get()
    if info is None:  # 最后的处理
      print ('put None')
      queue_after_downloader.put(None)
      break
    
    try:
      result  = requests.get(url).content
    except:
      continue

    queue_after_downloader.put(result)   # 解析后的结果再放入队列


def read_json():
    global queue_before_downloader

    with open('xxx.json', 'r') as f:
        lines = f.readlines()
    lines = [json.loads(x) for x in lines]
    print(len(lines))

    for _line in lines:
        queue_before_downloader.put(_line['url'])  # 把 url 保存在 before 队列之中

def main():

    start = time.time()

    global num_workers

    # 读取json文件中图像的url,放入多线程队列中
    read_json()

    global queue_before_downloader
    for _ in range(num_workers):   # 准备多个workers一起干活
        queue_before_downloader.put(None)

    processes = []
    for _ in range(num_workers):
        process = mp.Process(target=process_sample)   # 多进程处理函数
        processes.append(process)

    for process in processes:   # 启动进程
        process.start()
    
    num_completed = 0

    for _idx, items in enumerate(chunk(64, num_workers)):   # chunk 一个 batch 处理后的数据
        try:
            urls = items  # pairs; [url1, url2, ...,url64]
            num_completed += len(urls)
            print('--- {} : {} completed ---'.format(_idx+1, num_completed))
     
        except:
            #traceback.print_exc()
            continue

    for process in processes:   # 阻塞主进程,等待子进程的退出
        process.join()

if __name__ == "__main__":
    main()

相关文章

  • Python 多进程队列处理耗时操作的模版

    问题: requests.get(image_url).content 可以读取一个 image_url 中的内容...

  • Redis 实战 —— 09. 实现任务队列、消息拉取和文件分发

    任务队列 P133 通过将待执行任务的相关信息放入队列里面,并在之后对队列进行处理,可以推迟执行那些耗时对操作,这...

  • day 18

    part 1 进程 每个进程之间都是独立的,每个进程均运行在其专用且受保护的内存空间内 耗时操作耗时操作放到主线程...

  • iOS关于Dispatch优先级

    我们一般在使用异步队列处理耗时操作的时候会这样 而使用到的qos既DispatchQoS(Dispatch Qua...

  • dispatch_async 处理耗时操作的代码块...

    处理耗时操作的代码块...(可以多次请求数据库数据) 任务和队列 任务 就是执行操作的意思,换句话说就是你在线程中...

  • Dart-3的异步模型

    1-Dart的异步模型 1.1 如何处理耗时的操作呢? 针对如何处理耗时的操作,不同的语言有不同的处理方式。 处理...

  • python 进程,队列

    1.进程,队列 在python中虽然不能发挥多线程的优势,但是对于tensorflow中,多线程任务,我们可以写多...

  • Laravel - 队列学习一

    使用场景:处理一些耗时或者高并发的操作,把操作放到队列中异步执行,可以有效缓解系统压力、提高系 统响应速度和负载能...

  • Python并发编程——多进程

    摘要:Python,多进程 进程是操作系统中具体的处理任务,米一个进程都会有自己独立的内存空间,它是线程的载体。当...

  • Android基础之消息处理机制

    简介 消息驱动是一种进程/线程的运行模式,内部或者外部的消息事件被放到进程/线程的消息队列中按序处理是现在的操作系...

网友评论

      本文标题:Python 多进程队列处理耗时操作的模版

      本文链接:https://www.haomeiwen.com/subject/lcniiktx.html