Concurrency refers to the ability of a system to handle multiple tasks at once, making progress on more than one task in overlapping time periods. It is often used to design systems that can handle multiple inputs and outputs (I/O) efficiently, such as web servers handling multiple requests concurrently.
Parallelism, on the other hand, involves executing multiple tasks simultaneously, using multiple processors or cores. It focuses on improving computational speed by dividing tasks across different processing units.
Threading and multiprocessing are Python’s approaches to achieving concurrency and parallelism, each with its own strengths and use cases.
Example using threading:
import threading
def worker():
print("Thread working...")
# Create a thread
thread = threading.Thread(target=worker)
# Start the thread
thread.start()
# Wait for the thread to complete
thread.join()
Example using multiprocessing:
import multiprocessing
def worker():
print("Process working...")
# Create a process
process = multiprocessing.Process(target=worker)
# Start the process
process.start()
# Wait for the process to complete
process.join()
Example using asyncio:
import asyncio
async def main():
await asyncio.sleep(1)
print("Asyncio task completed")
# Run asyncio event loop
asyncio.run(main())
Example using concurrent.futures:
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def worker():
return "Worker executed"
# Using ThreadPoolExecutor
with ThreadPoolExecutor() as executor:
future = executor.submit(worker)
print(future.result())
# Using ProcessPoolExecutor
with ProcessPoolExecutor() as executor:
future = executor.submit(worker)
print(future.result())