Created
February 20, 2023 06:29
-
-
Save ankur0101/630c337f7beaaff10594cdebd093ac0a to your computer and use it in GitHub Desktop.
Python concurrency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from multiprocessing import Process, Pipe | |
def sleeper(seconds, conn): | |
time.sleep(seconds) | |
conn.send("Got up after "+str(seconds)+" seconds") | |
conn.close() | |
print("Processed: "+str(seconds)) | |
if __name__ == '__main__': | |
# create a list to keep all processes | |
processes = [] | |
# create a list to keep connections | |
parent_connections = [] | |
_start = time.time() | |
for sec in [2,5]: | |
# create a pipe for communication | |
parent_conn, child_conn = Pipe() | |
parent_connections.append(parent_conn) | |
# create the process, pass instance and connection | |
process = Process(target=sleeper, args=(sec, child_conn,)) | |
processes.append(process) | |
# start all processes | |
for process in processes: | |
process.start() | |
# make sure that all processes have finished | |
for process in processes: | |
process.join() | |
for pc in parent_connections: | |
print(pc.recv()) | |
_end = time.time() | |
total_time = _end - _start | |
print("Total time: "+str(total_time)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment