Skip to content

Instantly share code, notes, and snippets.

@Edmartt
Created December 20, 2023 08:16
Show Gist options
  • Save Edmartt/66aadcd814c645b6e09ebf20e737d491 to your computer and use it in GitHub Desktop.
Save Edmartt/66aadcd814c645b6e09ebf20e737d491 to your computer and use it in GitHub Desktop.
Python Concurrency and Parallelism
"""
This tiny test is the difference between concurrence and parallelism in Python.
With the multiprocessing module we have real access to parallelism always that we have more than one CPU core
"""
import os
from random import randint
from multiprocessing import Process
import time
articles = ["shoes", "t-shirts", "toys"] #simple in-memory database
def add_article(article: str):
"""adds new articles to the existant articles list
Args:
article (str): any string you want to add counts as new article
"""
articles.append(article)
def read_articles(args):
"""Print articles list
Args:
args (tuple): packed articles list and index for showing when printing
"""
articles, index = args
print("System process PID: {}".format(os.getpid())) # note that this time the PID is every for every thread, this means that every thread is a new process, just if we have several CPU cores
print("articles list #{}: {}".format(index, articles))
time_sleep = randint(1, 3)
time.sleep(time_sleep)
def create_thread(articles, index) -> Process:
"""Creates the needed thread
Args:
articles (list): needed list for showing with the read_article function
index (int): needed for printing the list number
Returns:
Process: run_thread function needs a process for running it, this is that process
"""
reader = Process(target=read_articles, args=[(articles, index)])
return reader
def run_thread(thread: Process):
"""Runs the process that we return from create_thread
Args:
thread (Process): process returned from create_thread function
"""
thread.start()
thread.join()
def show_menu() -> str:
""" Prints a menu for asking the user if wants to add new elements and return that answer
Returns:
str: answer typed
"""
valid_answer = ["y", "n"]
answer = input("do you want to add articles to the current list? (y/n)")
if answer in valid_answer:
return answer
return "This answer is not valid"
if __name__ == '__main__':
while True:
answer = show_menu()
match (answer): # we do a match and according to the answer some things could happen
case ("y"):
article = input("add article: ")
articles.append(article)
case ("n"): #if the user does not want to add new articles, we break this loop
break
case _:
print("not a valid option")
for i in range(0, 10): # we run a loop with 10 iterations just because we can :)
thread = create_thread(articles, i) # we send the list and the index, so we can print it in every process
run_thread(thread)
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment