IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /get-started.md). For the complete documentation index, see llms.txt.
Skip to main content
For the complete documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /get-started.md).

Mojo struct

Semaphore

struct Semaphore[origin: MutOrigin, //]

A device-wide semaphore implementation for GPUs.

This struct provides atomic operations and memory barriers for inter-CTA synchronization. It uses a single thread per CTA to perform atomic operations on a shared lock variable.

Implemented traits​

AnyType, Copyable, Deinitable, ImplicitlyCopyable, Movable, RegisterPassable, TrivialRegisterPassable

Methods​

__init__​

def __init__(lock: Pointer[Int32, origin], thread_id: Int) -> Self

Initialize a new Semaphore instance.

Args:

  • ​lock (Pointer[Int32, origin]): Pointer to shared lock variable in global memory.
  • ​thread_id (Int): Thread ID within the CTA, used to determine if this thread should perform atomic operations.

fetch​

def fetch(mut self)

Fetch the current state of the semaphore from global memory.

Only the designated wait thread (thread 0) performs the actual load, using an acquire memory ordering to ensure proper synchronization.

state​

def state(self) -> Int32

Get the current state of the semaphore.

Returns:

Int32: The current state value of the semaphore.

wait​

def wait(mut self, status: Int = Int(0))

Wait until the semaphore reaches the specified state.

Uses a barrier-based spin loop where all threads participate in checking the state. Only proceeds when the state matches the expected status.

Args:

  • ​status (Int): The state value to wait for (defaults to 0).

release​

def release(mut self, status: Int32 = Int32(0))

Release the semaphore by setting it to the specified state.

Ensures all threads have reached this point via a barrier before the designated thread updates the semaphore state.

Args:

  • ​status (Int32): The new state value to set (defaults to 0).