简体   繁体   中英

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:

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:

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? By using multiprocessing or subprocess modules?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM