简体   繁体   English

我正在尝试在 python 中使用多处理进行压缩

[英]I'm trying to use multiprocessing for compression in python

Here's what I'm trying to do-这就是我想要做的 -

import lz4.frame
import multiprocessing as mp

pool = mp.Pool(mp.cpu_count())
chunk_size = 64*1024
#screen is a pygame.Surface object converted to bytes

with lz4.frame.LZ4FrameCompressor(compression_level = 10, auto_flush = True) as compressor:
                compressed = pool.map(compressor.compress, [screen[i : i + chunk_size] for i in range(0, len(screen), chunk_size)])
                compressed = compressor.begin() + b''.join(compressed)
                compressed += compressor.flush()
pool.close()

This works just fine when I use map instead of pool.map... With pool.map, nothing happens.当我使用 map 而不是 pool.map 时,这工作得很好......使用 pool.map,没有任何反应。 Not even an error...甚至没有错误...

Also, what is the point of block_size argument in the compress function?另外,压缩函数中 block_size 参数的意义是什么? I tried different combinations of argument block_size (4 and 5) and chunk_size (64k and 256k), but it didn't seem to make much difference.我尝试了参数 block_size(4 和 5)和 chunk_size(64k 和 256k)的不同组合,但似乎没有太大区别。

Doing multiprocessing inside of a context can be hasardous if it is not fork safe.如果不是 fork 安全,在上下文中进行多处理可能会很麻烦。

In the doc ( https://python-lz4.readthedocs.io/en/stable/intro.html ) I read:在文档( https://python-lz4.readthedocs.io/en/stable/intro.html )中,我读到:

The bindings drop the GIL when calling in to the underlying LZ4 library, and is thread safe.调用底层 LZ4 库时,绑定会删除 GIL,并且是线程安全的。

Have you tried multithreading instead ?您是否尝试过多线程?

import lz4.frame
from concurrent.futures import ThreadPoolExecutor
import os

nb_chunk = 1024
chunk_size = 64*1024
screen = os.urandom(nb_chunk*chunk_size)

context = lz4.frame.create_compression_context()
chunks = [screen[i : i + chunk_size] for i in range(0, len(screen), chunk_size)]
contexts = [context] * len(chunks)
compressed = lz4.frame.compress_begin(context)
with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor:
    compressed_chunks = executor.map(lz4.frame.compress_chunk, contexts, chunks)
compressed += b''.join(compressed_chunks)
compressed = lz4.frame.compress_flush(context)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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