Skip to content

Mutex

Description

Mutex struct. Layout is platform-conditional but the API is uniform. Stack-declare with MutexInit(); do not poke fields.

Usage example (Cross-references)

Usage examples (Cross-references)
    ///     lock, kernel32, no init call needed (just zero-init).
    
    #include <Misra/Sys/Mutex.h>
    
    #include <Misra/Std.h>
    #endif
    
    void MutexDeinit(Mutex *m) {
        if (!m) {
            return;
        pthread_mutex_destroy(&m->_lock);
    #endif
        MemSet(m, 0, sizeof(Mutex));
    }
    }
    
    Mutex *MutexLock(Mutex *m) {
    #ifdef _WIN32
        // Cast through (SRWLOCK *) -- the header keeps `_lock` as a
    }
    
    Mutex *MutexUnlock(Mutex *m) {
    #ifdef _WIN32
        ReleaseSRWLockExclusive((SRWLOCK *)&m->_lock);
    #include <errno.h>
    
    #include <Misra/Sys/Mutex.h>
    
    // `ProcId` is part of the foundation because `LOG_FATAL` formats it
        pthread_mutex_t _lock;
    #endif
    } Mutex;
    
    ///
    #ifdef _WIN32
    // _lock is a void* layout-compatible with SRWLOCK. NULL = SRWLOCK_INIT.
    #    define MutexInit() ((Mutex) {._lock = NULL})
    #elif defined(__linux__) || defined(__APPLE__)
    // _Atomic int = 0 is "unlocked" in the futex / __ulock state machine.
    #elif defined(__linux__) || defined(__APPLE__)
    // _Atomic int = 0 is "unlocked" in the futex / __ulock state machine.
    #    define MutexInit() ((Mutex) {._state = 0})
    #else
    // PTHREAD_MUTEX_INITIALIZER is a static-init constant expression on
    // PTHREAD_MUTEX_INITIALIZER is a static-init constant expression on
    // every POSIX libc we target.
    #    define MutexInit() ((Mutex) {._lock = PTHREAD_MUTEX_INITIALIZER})
    #endif
    /// TAGS: Sys, Mutex, Deinit
    ///
    void MutexDeinit(Mutex *m);
    
    ///
    /// TAGS: Sys, Mutex, Lock
    ///
    Mutex *MutexLock(Mutex *m);
    
    ///
    /// TAGS: Sys, Mutex, Unlock
    ///
    Mutex *MutexUnlock(Mutex *m);
    
    #ifdef __cplusplus
Last updated on