首页 > python多进程Multiprocessing使用问题

python多进程Multiprocessing使用问题

代码:

# /usr/bin/python
#coding:utf-8

import multiprocessing,os,re,time

begintime = time.time()
def mtlogGzip(gzipfile):
    #print 'ddd'
    os.popen('tar -zcf %s.gz %s' %(gzipfile,gzipfile)).readline()

def muti_gzip():
    pool = multiprocessing.Pool(processes=4)
    for i in os.listdir('.'):
        if re.match(r'^20',i):
            print i
            pool.apply_async(mtlogGzip(i,))
    pool.close()
    pool.join()


if __name__=='__main__':
    muti_gzip()
endtime = time.time()
usetime =  endtime - begintime
print "执行脚本总用时 %s 秒" % usetime

执行后,ps,跟top看到的内容

ps

[root@localhost ~]# ps aux | grep test_gzip_02.py
root     16772  0.0  0.0 334716  7204 pts/0    Sl+  10:30   0:00 python test_gzip_02.py
root     16773  0.0  0.0 183148  4928 pts/0    S+   10:30   0:00 python test_gzip_02.py
root     16774  0.0  0.0 183148  4816 pts/0    S+   10:30   0:00 python test_gzip_02.py
root     16775  0.0  0.0 183148  4816 pts/0    S+   10:30   0:00 python test_gzip_02.py
root     16776  0.0  0.0 183148  4820 pts/0    S+   10:30   0:00 python test_gzip_02.py
root     16884  0.0  0.0 103248   872 pts/1    S+   10:35   0:00 grep test_gzip_02.py

top

17108 root      20   0  4296  676  308 S  4.3  0.0   0:25.13 gzip                                                                                                                      
17107 root      20   0  113m 1184  988 D  3.3  0.0   0:07.62 tar                                                                                                                                                                                                                                            
    1 root      20   0 19228  252  104 S  0.0  0.0   0:03.54 init                                                                                                                      
    2 root      20   0     0    0    0 S  0.0  0.0   0:11.86 kthreadd                                                                                                                  
    3 root      RT   0     0    0    0 S  0.0  0.0   0:24.89 migration/0                                                                                                               
    4 root      20   0     0    0    0 S  0.0  0.0   0:18.39 ksoftirqd/0 

可以看到top里面只有一个tar,一个gzip在执行操作,并没有多个同时进行压缩操作,这是为什么的?


apply_async(func[, args[, kwds[, callback]]])
A variant of the apply() method which returns a result object.

以上是apply_async的函数原型,参数传递有问题,apply_async的第一个参数是函数对象,第二个参数是函数对象的参数,你把参数也写到第一个参数里,相当于调用函数,把函数的执行结果当第一个参数传递给了apply_async,所以等于是同步执行,正确的姿势用如下方式调用:

pool.apply_async(mtlogGzip,(i,))
【热门文章】
【热门文章】