• Python 多进程应用示例


    import multiprocessing
    import time
    
    def func(name):
    	outputline=name
    	for i in range(3):
    		outputline+= " repeat "+str(i)
    		time.sleep(1)
    	return outputline
    
    def main():
    	pool=multiprocessing.Pool(processes=4)
    	result=[]
    	for i in range(4):
    		pname="cpu_%d"%i
    		result.append(pool.apply_async(func, (pname, )))
    	pool.close()
    	pool.join()
    	for res in result:
    		print res.get()
    	print "all processes done"
    
    if __name__ == '__main__':
    	main()
    

     示例2,使用锁同步

    import multiprocessing
    import time
    
    def func(name,lock):
    	outputline=name
    	for i in range(3):
    		outputline+= " repeat "+str(i)
    		lock.acquire()
    		print name+" repeat "+str(i)
    		lock.release()
    		time.sleep(1)
    	return outputline
    
    def main():
    	lock=multiprocessing.Lock()
    	subprocesses=[]
    	for i in range(4):
    		pname="cpu_%d"%i
    		process=multiprocessing.Process(target=func, args=(pname,lock))
    		process.start()
    		subprocesses.append(process)
    	
    	for p in subprocesses:
    		p.join()
    
    	print "all processes done"
    
    if __name__ == '__main__':
    	main()
    

    ref:

    http://www.coder4.com/archives/3352

    http://www.cnblogs.com/vamei/archive/2012/10/12/2721484.html

  • 相关阅读:
    vbscript 语言通过序列和ADODB实现取号不重复
    arcgisserver成功发布服务后,浏览服务,无地图显示
    GUID的获取
    EasyUi 表格自适应宽度
    接口隔离原则
    依赖倒置原则
    开放封闭原则
    单一职责原则
    python-函数基础
    python -流程控制
  • 原文地址:https://www.cnblogs.com/plwang1990/p/4386316.html
Copyright © 2020-2023  润新知