Browse Chunks

Showing 5151-5200 of 7392 chunks

import threading
CAT_5

Imports the threading module to enable creation and management of threads in a Python program. This statement makes the threading namespace available for use, allowing developers to spawn concurrent threads.

import module

t = threading.Thread(target=my_function, args=(arg1, arg2))
CAT_5

Instantiates a new thread object that will execute a given callable in a separate OS thread when started. Addresses the pain point of blocking the main thread during I/O-bound or long-running operations. Reached for when a task can run independently without needing to block the caller.

thread = threading.Thread(target=function, args=(arg1, arg2))

t.start()
CAT_5

Begins execution of a Thread object's target function in a separate thread of control. Solves the problem of offloading blocking or I/O-bound work so the calling thread remains responsive. Reached for once a Thread instance is fully configured and concurrent execution needs to begin.

thread.start()

t.join()
CAT_5

The t.join() call blocks the current thread of execution until the thread represented by t completes its work. It is used to synchronize threads and ensure that any shared resources accessed by the thread are safely available after the join returns. An optional timeout can be specified to limit the wait time.

thread.join(timeout)

with lock:
CAT_5

Acquires a lock using Python's context manager protocol, ensuring the lock is released automatically when the block exits even if an exception occurs. Addresses the pain point of forgotten lock releases causing deadlocks or race conditions when exceptions interrupt critical sections. Reached for whenever multiple threads access shared mutable state that requires mutual exclusion.

with lock:

event.wait()
CAT_5

The event.wait() method blocks the calling thread until another thread sets the associated Event, or until an optional timeout expires. It is used to synchronize threads by waiting for a signal.

event.wait(; )

threading.Timer(interval, func, args).start()
CAT_5

threading.Timer creates a timer that calls a given function after a specified interval, allowing delayed execution without blocking the main thread. The timer is started immediately with .start().

threading.Timer(delay_seconds, callback, callback_args).start()

p = Process(target=worker, args=(arg,))
CAT_5

Creates a new Process object that will execute the worker function with the supplied argument in a separate process.

p = Process(target=callable, args=(arg,))

p.start()
CAT_5

Starts a new thread or process by calling its start() method, which begins concurrent execution of the target function. Returns immediately; the caller must join() to wait for completion.

process.start()

p.join()
CAT_5

Waits for a process or thread to finish execution before continuing. Used to synchronize the main program with concurrent workers.

;.join()

asyncio.run(main())
CAT_5

Creates a new asyncio event loop, runs the supplied coroutine to completion, then closes the loop — serving as the standard bridge from synchronous to asynchronous execution. Solves the bootstrapping problem where async code cannot run without an event loop but synchronous entry points have no loop running. Reach for this at any script's top level when you need to kick off an async program.

asyncio.run(coroutine)

asyncio.get_event_loop()
CAT_5

Retrieves the current event loop in the asyncio runtime, creating one if none exists in the current OS thread. Addresses the need to access the event loop for scheduling coroutines and callbacks when a running loop is not already available. Reached for when integrating synchronous code with async execution or manually driving coroutines.

loop = asyncio.get_event_loop()

await asyncio.sleep
CAT_5

Suspends the current coroutine for a specified number of seconds while yielding control back to the event loop so other tasks can execute. It addresses the problem of blocking the entire event loop with a synchronous delay, which would freeze all concurrent coroutines. Reach for it whenever you need a non-blocking pause, such as throttling requests, simulating latency in tests, or implementing retry backoff.

await asyncio.sleep(duration)

await asyncio.gather
CAT_5

Awaits the concurrent execution of multiple awaitable objects (e.g., coroutines, Tasks) and returns their results in the order of the input awaitables.

await asyncio.gather(awaitable1, awaitable2, ...)

loop.create_task(my_coro())
CAT_5

Schedules a coroutine to run concurrently as a Task on the given event loop, returning the Task object. This allows the coroutine to start executing without blocking the current flow, and the task can be awaited or cancelled later.

loop.create_task(coro())

asyncio.wait_for
CAT_5

asyncio.wait_for wraps an awaitable with a timeout, cancelling it and raising TimeoutError if the operation does not complete within the given time. It is used to bound the execution time of asynchronous operations and avoid indefinite hanging.

asyncio.wait_for(awaitable, timeout=timeout_seconds)

asyncio.shield(my_coro())
CAT_5

asyncio.shield wraps a coroutine so that it is protected from cancellation; if the surrounding task is cancelled, the shielded coroutine continues to run until completion, and its result or exception is propagated.

asyncio.shield(coro())

asyncio.get_running_loop()
CAT_5

Returns the currently running asyncio event loop, providing direct access to loop-level operations such as scheduling callbacks or creating tasks. Solves the pain point of needing loop access in library code without requiring the loop to be passed as an explicit parameter or resorting to the deprecated asyncio.get_event_loop(). Must be called from within an already-running event loop or it raises RuntimeError.

asyncio.get_running_loop()

loop.call_soon
CAT_5

Schedules a callback to be called as soon as possible in the event loop, after the current control yields back to the loop.

loop.call_soon(callback, *args)

asyncio.run_coroutine_threadsafe
CAT_5

Runs a coroutine in a given event loop from another thread, returning a concurrent.futures.Future that can be used to retrieve the result or exception. This bridges threading and asyncio by safely scheduling the coroutine on the target loop.

asyncio.run_coroutine_threadsafe(coro, loop)

async def fetch_data():
CAT_5

Defines an asynchronous function (coroutine) that can be awaited to perform non‑blocking operations, typically I/O‑bound work such as network requests or file access.

async def function_name(parameters): ...

async with lock:
CAT_5

Acquires an asyncio lock for exclusive access within an async context manager, automatically releasing it when the block exits. Addresses race conditions where multiple coroutines access shared mutable state concurrently. Used whenever coordinated exclusive access to a shared resource is needed in an asynchronous program.

async with lock:

result = await coro()
CAT_5

Assigns the return value of an awaited coroutine or awaitable to a local variable, suspending the enclosing coroutine until the awaitable completes. Addresses the pain point of needing the concrete result of an asynchronous operation before proceeding with dependent logic. Triggered whenever an async function must use the outcome of another async call rather than fire-and-forget.

result = await awaitable

async for item in async_iterable:
CAT_5

Iterates asynchronously over an asynchronous iterable, awaiting each item as it becomes available. Use when you need to process items from an async source such as an async generator, network stream, or async queue without blocking the event loop.

async for item in async_iterable:

await asyncio.shield(coro())
CAT_5

Wraps a coroutine so that if the outer awaiting task is cancelled, the inner coroutine continues running instead of being cancelled. This addresses the pain point of critical background operations (like database commits or cleanup) being prematurely aborted when a parent task receives a cancellation request. You reach for it whenever a coroutine must complete even if the caller is cancelled.

await asyncio.shield(coro())

tasks =
CAT_5

Creates a list of asyncio.Task objects by invoking a coroutine function multiple times in a list comprehension. Use it when you need to fire off several independent asynchronous operations concurrently and keep references to their tasks for later awaiting or cancellation.

tasks = [asyncio.create_task(coro(item)) for item in collection]

done, pending = await asyncio.wait
CAT_5

Waits for multiple asyncio tasks to complete, splitting results into done and pending sets based on a timeout or completion condition. Addresses the need to process results as soon as any task finishes rather than blocking until all tasks complete. Reached for when you need to react to partial completion, enforce deadlines, or iteratively process finished work while letting remaining tasks continue.

done, pending = await asyncio.wait(tasks, timeout=seconds, return_when=condition)

async with asyncio.timeout(seconds):
CAT_5

Creates an asynchronous context manager that cancels all enclosed tasks after a specified duration, raising TimeoutError. Addresses the pain point of unbounded waits in async pipelines where a single stalled coroutine can block an entire event loop. Reach for this whenever a group of async operations must complete within a hard deadline rather than hanging indefinitely.

async with asyncio.timeout(duration):

asyncio.create_task(my_coroutine())
CAT_5

Schedules the given coroutine to run concurrently as a Task and returns the Task object.

asyncio.create_task(<coroutine>)

task.result()
CAT_5

Retrieves the return value of a completed Future or Task, re-raising any exception that occurred during execution. It addresses the need to explicitly extract an outcome when you cannot or choose not to use await, such as in callback-based or testing code. You reach for it when a Future is confirmed done and you need its value or want to surface its exception.

task.result(timeout=timeout)

await asyncio.gather
CAT_5

Runs multiple awaitable coroutines concurrently and collects all their results into a list in submission order. Addresses the pain point of sequential await calls that waste wall-clock time waiting for independent I/O operations one after another. Reached for whenever two or more independent async tasks must complete before proceeding.

await asyncio.gather(*coroutines)

asyncio.wait
CAT_5

Waits for multiple awaitables and returns as soon as the first one completes, yielding two sets (done and pending). Addresses the need to proceed with the fastest result without blocking on slower tasks. Reached for when you need racing semantics or want to react to the first available result.

asyncio.wait([task1, task2], return_when=asyncio.FIRST_COMPLETED)

asyncio.wait_for
CAT_5

Wraps an awaitable with a deadline, cancelling it and raising TimeoutError if it exceeds the specified timeout in seconds. Addresses the pain point of coroutines that may hang indefinitely on unresponsive network services or stalled subprocesses. Reached for whenever an async operation must be bounded in time to maintain system responsiveness or implement fallback logic.

asyncio.wait_for(awaitable, timeout)

asyncio.all_tasks()
CAT_5

Returns a set of all currently pending asyncio.Task objects in the running event loop.

asyncio.all_tasks()

asyncio.shield
CAT_5

Wraps an awaitable so that cancellation requests cannot reach it, allowing the inner coroutine or Task to run to completion even when the caller is cancelled. Without shielding, a long-running critical operation like a database commit or resource release can be interrupted mid-execution, leaving the system in an inconsistent state. Reach for shield when an operation must finish regardless of whether the surrounding task receives a cancellation signal.

asyncio.shield(task)

asyncio.get_event_loop()
CAT_5

Returns the current asyncio event loop, creating a new one if none is set for the current thread. Used to obtain the loop for low-level control of coroutines, callbacks, and task scheduling.

asyncio.get_event_loop()

await asyncio.sleep
CAT_5

Yields control back to the asyncio event loop, allowing other tasks to run without actually sleeping.

await asyncio.sleep(delay)

await semaphore.acquire()
CAT_5

Acquires a slot in an asyncio semaphore, waiting asynchronously if the internal counter is zero. It solves the problem of unbounded concurrency overwhelming a rate-limited resource. Reach for it when you need to manually control the entry and exit of a critical section or shared resource, though `async with` is usually preferred.

await semaphore.acquire()

await lock.acquire()
CAT_5

Asynchronously acquires an asyncio lock, suspending the current coroutine until the lock is available. It addresses the pain point of race conditions on shared mutable state in concurrent async code. It is triggered when entering a critical section that requires mutual exclusion without blocking the event loop.

await lock.acquire(timeout=value)

await barrier.wait()
CAT_5

Waits until all participating coroutines have reached the barrier point, then releases them to continue.

await barrier.wait()

await lock.release()
CAT_5

Releases an asynchronous lock, allowing other waiting coroutines to acquire it and proceed. Addresses the need to safely yield exclusive access in concurrent async code. Triggered when a critical section or shared resource operation is complete.

await lock.release()

await condition.notify_all()
CAT_5

Wakes up all coroutines waiting on an asyncio.Condition so they can reacquire the lock and re-check shared state. Solves the lost-signal problem where some waiters might never resume if only a single notify() is issued. Reach for this when a state change is relevant to every blocked task, such as a buffer refill or a shutdown signal.

await condition.notify_all()

await event.clear()
CAT_5

Resets an asyncio.Event's internal flag to False, causing subsequent calls to wait() to block until set() is called again. Used to re-arm an event for the next signaling cycle after a wait() has returned. Essential for implementing cyclic signaling patterns between coroutines.

event.clear()

await barrier.reset()
CAT_5

Resets an asyncio.Barrier to its initial empty state so it can be reused for another synchronization phase. Without reset, a barrier that has been aborted remains broken and any subsequent wait() calls will immediately raise BrokenBarrierError. Reach for this after handling a broken barrier when you want to retry the synchronization rather than creating a new Barrier instance.

await barrier.reset()

with ThreadPoolExecutor(max_workers=4) as executor:
CAT_5

Creates a thread pool executor with a maximum of 4 worker threads and binds it to the variable `executor` for use within a `with` block, ensuring automatic shutdown after the block.

with ThreadPoolExecutor(max_workers=num_workers) as executor:

executor.submit
CAT_5

Schedules a callable to be executed concurrently in a thread or process pool and returns a Future object representing its execution. It addresses the need to run blocking or CPU-intensive tasks without stalling the main thread. Reach for this when you need to offload a specific function call to a background worker pool.

executor.submit(callable, *args, **kwargs)

list(executor.map(task_func, iterable))
CAT_5

Applies a callable to every item in an iterable using a thread or process pool, collecting all results into a list in input order. Eliminates the boilerplate of manually submitting tasks and waiting on futures when you simply need all outputs. Reach for this when you have many independent, similarly-shaped tasks and want parallel speedup without managing individual futures.

list(executor.map(task_func, iterable))

future.result()
CAT_5

Blocks the calling thread until a Future's result is available, then returns the value or re-raises any exception from the computation. Solves the problem of needing a computed value from a background task before the main thread can continue. Reached for whenever a submitted task must complete before downstream logic runs.

future.result(timeout=None)

[f.result() for f in concurrent.futures.as_completed(futures)]
CAT_5

Collects the return values of submitted Future objects in the order they complete rather than the order they were submitted. It solves the problem of needing to wait for all tasks to finish before processing any results, which wastes time when some tasks finish much earlier than others. Reach for this when you have multiple concurrent tasks with variable durations and want to process each result as soon as it becomes available.

[future.result() for future in concurrent.futures.as_completed(futures)]

executor.map
CAT_5

Applies a given function to each item in an iterable concurrently using a thread or process pool, with a timeout for each individual call.

executor.map(callable, iterable, timeout=timeout)