[英]How to execute processes in serial and in parallel using python
How can i create a process execution in serial fashion vs parallel fashion? 如何以串行方式与并行方式创建流程执行?
For example i want each process to execute the following python function: 例如,我希望每个进程执行以下python函数:
def execute():
time.sleep(random.randint(0,9))
If i run the processes like: 如果我运行类似的过程:
for process in process_list:
process.run()
Given a scenario of only 2 processes in a serial fahsion i would expect the output of the program to be exatcly: 给定一个串行 fahsion中只有2个进程的情况,我希望程序的输出是完美的:
process 1 - start
process 1 - end
process 2 - start
process 2 - end
In a parallel scenario i would expect a possible output such as: 在并行场景中,我期望可能的输出,例如:
process 1 - start
process 2 - start
process 2 - end
process 1 - end
How can i replicate these two scenarios in python with a processing module? 如何使用处理模块在python中复制这两种情况? By using
multiprocessing
or subprocess
modules? 通过使用
multiprocessing
或subprocess
模块?
Use the threading built in library. 使用内置库中的线程。
Create your thread with 创建您的线程
thread = threading.thread()
start it with 从开始
thread.start()
and then, within the thread's execution, call 然后在线程的执行中,调用
otherThread.join()
to form a sequential/serial queue in which the calling thread executes after the called thread. 形成一个顺序/串行队列,在该队列中,调用线程在被调用线程之后执行。
https://docs.python.org/2/library/threading.html https://docs.python.org/2/library/threading.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.