码迷,mamicode.com
首页 > 编程语言 > 详细

python多进程并行代码

时间:2019-09-30 09:28:18      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:进程   tar   name   join   优化   lock   style   targe   多进程   

from multiprocessing import Process
import sys, os
import time


def timetask(string):
  while True:
    print(string)


def works(func, arg, worknum):
  proc_record = []
  for i in range(worknum):
    p = Process(target = func, args = (i,))
    p.start()
    proc_record.append(p)
  for p in proc_record:
    p.join()


if __name__ == __main__:
  arg = 5
  procs = 4
  works(timetask, arg, procs)

 

效果图【未加锁,会发现数字1没出现,进程间资源抢夺导致】:

技术图片

 

 

 

优化之后效果:

技术图片

 

 

代码:

from multiprocessing import Process
import sys, os
import time
from threading import Lock


def timetask(string):
  mutex.acquire()
  while True:
    print(string)
    if mutex.locked():
      mutex.release()


mutex = Lock()

def works(func, arg, worknum):
  proc_record = []
  for i in range(worknum):
    p = Process(target = func, args = (i,))
    p.start()
    proc_record.append(p)
  for p in proc_record:
    p.join()


if __name__ == __main__:
  arg = 5
  procs = 4
  works(timetask, arg, procs)

 

python多进程并行代码

标签:进程   tar   name   join   优化   lock   style   targe   多进程   

原文地址:https://www.cnblogs.com/codeDevotee/p/11610759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!