Junior — Middle
What methods can be used to control the number of threads or tasks running simultaneously when accessing a resource within a given time period?
sobes.tech AI
Answer from AI
In Python, to control the number of threads or tasks executing simultaneously when accessing a resource, the following are often used:
- Semaphore from the
threadingorasynciomodule — limits the number of threads or coroutines running at the same time. - ThreadPoolExecutor or ProcessPoolExecutor from the
concurrent.futuresmodule — manage a pool of threads or processes. - asyncio.BoundedSemaphore — for asynchronous code.
Example with a semaphore:
import threading
semaphore = threading.Semaphore(3) # maximum 3 threads at the same time
def task():
with semaphore:
# access to resource
pass
This approach allows limiting parallelism and avoiding resource overload.