Junior — Middle
Kas Pythonis on võimalik teha mitu ülesannet samaaegselt ühes lõimes?
sobes.tech AI
Vastus AI-lt
In Python, in a single thread, multiple tasks can be executed simultaneously using asynchronous programming (asyncio) or generators, which allow switching between tasks without creating new threads. However, due to GIL (Global Interpreter Lock) in the standard implementation of CPython, concurrent execution of multiple threads running Python code is limited — only one thread executes at any given time.
Example with asyncio for concurrent execution of tasks in a single thread:
import asyncio
async def task(name, delay):
await asyncio.sleep(delay)
print(f"Task {name} completed")
async def main():
await asyncio.gather(
task('A', 1),
task('B', 2),
task('C', 1.5)
)
asyncio.run(main())
This way, multiple tasks can be executed "in parallel" in a single thread, switching based on the wait time, but not simultaneously in the sense of multithreading.