6

我想使用我的 8 核 16 GB ram 工作站快速 bzip2 压缩数百 GB 的数据。目前我正在使用一个简单的 python 脚本来压缩整个目录树,它使用 bzip2 和一个耦合到 os.walk 调用的 os.system 调用。

我看到 bzip2 只使用一个 cpu,而另一个 cpu 保持相对空闲。

我是队列和线程进程的新手。但我想知道如何实现这一点,以便我可以有四个 bzip2 运行线程(实际上我猜是 os.system 线程),每个线程可能使用自己的 cpu ,当他们 bzip 文件时从队列中耗尽文件。

我的单线程脚本粘贴在这里。

import os
import sys

for roots, dirlist , filelist in os.walk(os.curdir):
    for file in [os.path.join(roots,filegot) for filegot in filelist]:
        if "bz2" not in file:
            print "Compressing %s" % (file)
            os.system("bzip2 %s" % file)
            print ":DONE" 
4

2 回答 2

1

在 comp.lang.python 上尝试来自 MRAB 的这段代码:

import os 
import sys 
from threading import Thread, Lock 
from Queue import Queue 
def report(message): 
     mutex.acquire() 
     print message 
     sys.stdout.flush() 
     mutex.release() 
class Compressor(Thread): 
     def __init__(self, in_queue, out_queue): 
         Thread.__init__(self) 
         self.in_queue = in_queue 
         self.out_queue = out_queue 
     def run(self): 
         while True: 
             path = self.in_queue.get() 
             sys.stdout.flush() 
             if path is None: 
                 break 
             report("Compressing %s" % path) 
             os.system("bzip2 %s" % path) 
             report("Done %s" %  path) 
             self.out_queue.put(path) 
in_queue = Queue() 
out_queue = Queue() 
mutex = Lock() 
THREAD_COUNT = 4 
worker_list = [] 
for i in range(THREAD_COUNT): 
     worker = Compressor(in_queue, out_queue) 
     worker.start() 
     worker_list.append(worker) 
for roots, dirlist, filelist in os.walk(os.curdir): 
     for file in [os.path.join(roots, filegot) for filegot in filelist]: 
         if "bz2" not in file: 
             in_queue.put(file) 
for i in range(THREAD_COUNT): 
     in_queue.put(None) 
for worker in worker_list: 
     worker.join() 
于 2010-10-22T01:25:24.850 回答
1

使用该subprocess模块一次生成多个进程。如果其中 N 个正在运行(N 应该比您拥有的 CPU 数量大一点,例如 3 个用于 2 个内核,10 个用于 8 个),请等待一个终止,然后再启动另一个。

请注意,这可能没有多大帮助,因为会有很多您无法并行化的磁盘活动。大量用于缓存的空闲 RAM 会有所帮助。

于 2010-07-27T15:32:33.363 回答