Mutex API

The Mutex API provides lightweight thread synchronization inside AngelScript. Mutex objects are native engine primitives exposed as mutex_t handles. They support:

  • Exclusive locks (writers)

  • Shared locks (readers)

  • Non-blocking try-lock operations

  • Automatic cleanup on script shutdown

Mutexes are created by create_mutex() and manually released using destroy()


πŸ”‘ Creating Mutexes

Create

mutex_t create_mutex();

Creates a new mutex and registers it with the current AngelScript context.

Example:

mutex_t m = create_mutex();

Destroy

void mutex_t::destroy();

Frees the underlying native mutex.

Note: If the script forgets to call destroy(), the PCX engine frees all remaining mutexes when the script context unloads.

Example:


πŸ” Exclusive Lock (Writer Lock)

Use these when only one thread should modify shared state.

Lock (blocking)

Blocks until exclusive ownership is acquired.

Try Lock (non-blocking)

Returns true if the lock is acquired immediately, false otherwise.

Unlock

Releases the exclusive lock.


πŸ“– Shared Lock (Reader Lock)

Shared locks allow multiple readers, but automatically block if an exclusive writer holds the lock.

Lock Shared (blocking)

Blocks until a shared lock is available.

Try Lock Shared (non-blocking)

Returns immediately with true on success.

Unlock Shared

Releases the shared lock.


🧩 Usage Example


πŸ—‘ Automatic Cleanup

Even if a script forgets:

PCX will:

  • Free each mtx_t safely

  • Avoid leaks and invalid handles


Avoid Deadlocks!

  • You must avoid deadlocks

  • If an exception happens and the active thread had a lock, It will cause a deadlock

  • Use the following try & catch logic to avoid it.

Last updated