Describe Python's asyncio.gather and its usage.
asyncio.gather is used to run multiple coroutines concurrently and aggregate their results. It helps in managing several tasks simultaneously.
import asyncio
async def factorial(name, number):
f = 1
for i in range(2, number + 1):
print(f"Task {name}: Compute factorial({i})...")
await asyncio.sleep(1)
f *= i
print(f"Task {name}: factorial({number}) = {f}")
return f
async def main():
# Schedule three calls *concurrently*:
results = await asyncio.gather(
factorial("A", 2),
factorial("B", 3),
factorial("C", 4),
)
print(results)
asyncio.run(main())
Thread-safe singleton Class in Python
import threading
class Singleton:
_instance = None
_lock = threading.Lock() # Lock object to synchronize threads
def __new__(cls):
with cls._lock: # Critical section starts
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance