利用工厂模式处理并发与顺序两种执行方式
程序员文章站
2022-07-14 16:57:08
...
在程序中经常会用到并发与顺序执行的情况,在每次需要并发的时候,再去分配线程的话,会显得整个代码很乱,所以,在这里我用一个工厂类ExecutorFactory来创建不同的执行类:ConcurExecutor和SequenExecutor。
先看看代码再说:
ExecutorFactory.py:
ConcurExecutor.py:
SequenExecutor.py:
我们使用的时候可以这样写:
这样,当我们的项目里,多个地方需要并发或顺序处理的时候,就不会很混乱了。
先看看代码再说:
ExecutorFactory.py:
from ConcurExecutor import ConcurExecutor from SequenExecutor import SequenExecutor class ExecutorFactory: def __init__(self): pass def createExecutor(self, type): if "concurrence" == type: executor = ConcurExecutor() elif "sequence" == type: executor = SequenExecutor() return executor
ConcurExecutor.py:
import threading class JobThread(threading.Thread): def __init__(self, func, args): threading.Thread.__init__(self) self.func = func self.args = args self.result = False def run(self): self.result = apply(self.func, self.args) def getResult(self): return self.result class ConcurExecutor: def __init__(self): self.jobList = [] def addJob(self, jobFunc, jobArgs, env): jobThread = JobThread(jobFunc, (jobArgs, env)) self.jobList.append(jobThread) def execJobs(self): for jobThread in self.jobList: jobThread.start() for jobThread in self.jobList: jobThread.join() def isAllSucc(self): for jobThread in self.jobList: if False == jobThread.getResult(): return False return True
SequenExecutor.py:
class SequenExecutor: def __init__(self): self.jobList = [] self.resultList = [] def addJob(self, jobFunc, jobArgs, env): job = (jobFunc, jobArgs, env) self.jobList.append(job) def execJobs(self): for job in self.jobList: result = job[0](job[1], job[2]) self.resultList.append(result) def isAllSucc(self): if all(result for result in self.resultList): return True return False
我们使用的时候可以这样写:
executorFactory = ExecutorFactory() executor = executorFactory.createExecutor('sequence') #当然这里也可以改成并发 for elm_scene in elm_branch.getchildren(): executor.addJob(SceneAction, (elm_scene, brchLogger), envClone(env)) executor.execJobs() result = executor.isAllSucc()
这样,当我们的项目里,多个地方需要并发或顺序处理的时候,就不会很混乱了。
上一篇: 数据库ID字段的设计