python 并发执行

  • 并发执行, 精简代码。 适用python2 和python3
# -*- encoding:utf-8 -*-
from threading import Thread
from multiprocessing import Process

def parProcess(worker, m_args=[(i,) for i in range(5)]):
    threads = [Process(target=worker, args=arg) for arg in m_args]
    start   = [th.start() for th in threads ] 
    ended   = [th.join()  for th in threads ]

def parThread(worker, m_args=[(i,) for i in range(5)]):    
    threads = [Thread(target=worker, args=arg) for arg in m_args]
    start   = [th.start() for th in threads]
    ended   = [th.join() for th in threads]

def _worker(i):
    print('Thread = %d ' % i)
    
def _tt():
    print('Thread tt')

#parProcess(_worker) # 必须在main 模块中调用  
#parThread(_worker)  # 可以运行
    
if __name__ == '__main__':
    print('1.----')
    parProcess(_worker)
    print('2.----')
    parThread(_worker)
    print('3.----')
    parProcess(_tt, [() for i in range(5)] )
    


--- 她说, 她是仙,她不是神
原文地址:https://www.cnblogs.com/bregman/p/5018723.html