Discuss / Python / 学习 python multiprocessing 多进程遇到的一些问题

学习 python multiprocessing 多进程遇到的一些问题

Smaiilv

#1 Created at ... [Delete] [Delete and Lock User]

代码:

#coding: utf-8
import multiprocessing
import time

def func(msg):
    print "msg:", msg
    time.sleep(1.5)
    print "end"

counter = 0
if __name__ == "__main__":
    pool = multiprocessing.Pool(processes = 4)

    for i in xrange(10):
        pool.apply_async(func, (i, ))

    print "Sub-process(es) Start."
    pool.close()
    pool.join()   
    print "Sub-process(es) Done."

print 'test-',counter #问题语句
counter += 1

输出结果:

Sub-process(es) Start.
test- 0
msg: 2
end
msg: 6
end
test- 0
msg: 3
end
msg: 7
end
test- 0
msg: 0
end
msg: 4
end
msg: 8
end
test- 0
msg: 1
end
msg: 5
end
msg: 9
end
Sub-process(es) Done.
test- 0
[Finished in 4.8s]

我有点不明白, 以下语句不属于输入进程池的函数, 但是却执行了几遍, 为什么会这样?

print 'test-',counter

  • 1

Reply