Name ways to perform competitive code execution in Python
sobes.tech AI
Answer from AI
Python offers several ways to perform concurrent code execution:
-
Threads (threading) — allow running multiple threads within a single process. Due to the GIL (Global Interpreter Lock), threads do not provide true parallelism for CPU-intensive tasks, but are useful for I/O-bound operations.
-
Multiprocessing — creates separate processes, each with its own memory and Python interpreter, which helps bypass the GIL and achieve true parallelism for CPU-intensive tasks.
-
Asynchronous programming (asyncio) — based on an event loop and coroutines, effective for handling a large number of I/O-bound tasks without creating threads or processes.
-
Concurrent.futures — a high-level interface for running tasks in threads or processes.
Example of using multiprocessing:
from multiprocessing import Pool
def f(x):
return x * x
if __name__ == '__main__':
with Pool(4) as p:
print(p.map(f, [1, 2, 3, 4]))
Example with asyncio:
import asyncio
async def main():
print('Hello')
await asyncio.sleep(1)
print('World')
asyncio.run(main())