Analytics Vidhya
Published in

Analytics Vidhya

Multithreading and Multiprocessing in Python

Process vs. Thread

Global Interpreter Lock (GIL)

Multithreading

import time
import threading
def some_task():
time.sleep(1)
print("Finished task")
if __name__ == "__main__":
start = time.time()
# Create two threads
t1 = threading.Thread(target=some_task)
t2 = threading.Thread(target=some_task)
# Start running both threads
t1.start()
t2.start()
# Wait until both threads are complete, and join the process into a single thread
t1.join()
t2.join()
end = time.time() print(f"Finished process in {end - start} seconds")

Multiprocessing

import time
import multiprocessing
def some_task():
for _ in range(100_000_000):
x = 1 + 1
print("Finished task")
if __name__ == "__main__":
start = time.time()
# Create two threads
p1 = multiprocessing.Process(target=some_task)
p2 = multiprocessing.Process(target=some_task)
# Start running both threads
p1.start()
p2.start()
# Wait until both threads are complete, and join the process into a single thread
p1.join()
p2.join()
end = time.time() print(f"Finished process in {end - start} seconds")

concurrent.futures

Shared Memory and Race Conditions

--

--

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store