/*
 * SPDX-FileCopyrightText: (c) 2009 RWTH Aachen University <rwth-aachen.de>
 * SPDX-FileCopyrightText: (c) 2009 Gesellschaft für numerische Simulation mbH Braunschweig <gns-mbh.com>
 * SPDX-FileCopyrightText: (c) 2009 Technische Universität Dresden <tu-dresden.de>
 * SPDX-FileCopyrightText: (c) 2009 University of Oregon <uoregon.edu>
 * SPDX-FileCopyrightText: (c) 2009 Forschungszentrum Jülich GmbH <fz-juelich.de>
 * SPDX-FileCopyrightText: (c) 2009 German Research School for Simulation Sciences GmbH
 * SPDX-FileCopyrightText: (c) 2009 Technische Universität München <tum.de>
 *
 * SPDX-License-Identifier: BSD-3-Clause
 *
 */



#ifndef UTILS_MUTEX_H
#define UTILS_MUTEX_H


/**
 * @file
 *
 *
 * Abstract locking object.
 *
 * Usage:
 * @code
 *     UTILS_Mutex lock = UTILS_MUTEX_INIT;
 *     :
 *     UTILS_MutexLock( &lock );
 *     : <critical section>
 *     UTILS_MutexUnlock( &lock );
 * @endcode
 *
 */


#ifndef __cplusplus
#include <stdbool.h>
#endif

#include <UTILS_Atomic.h>

#if HAVE( GCC_ATOMIC_BUILTINS )
#define STATIC_INLINE static inline
#else /* !GCC_ATOMIC_BUILTINS */
#define STATIC_INLINE
#endif /* !GCC_ATOMIC_BUILTINS */

/**
 * A lock object is just a bool. Should be 0-initialized if allocated.
 */
typedef bool UTILS_Mutex;

/**
 * Initialize an mutex variable to the unlocked state.
 */
#define UTILS_MUTEX_INIT false


UTILS_BEGIN_C_DECLS

#define UTILS_MutexLock PACKAGE_MANGLE_NAME( UTILS_MutexLock )
STATIC_INLINE void
UTILS_MutexLock( UTILS_Mutex* mutex );

/* Try to acquire the lock, returns true on success */
#define UTILS_MutexTrylock PACKAGE_MANGLE_NAME( UTILS_MutexTrylock )
STATIC_INLINE bool
UTILS_MutexTrylock( UTILS_Mutex* mutex );

#define UTILS_MutexUnlock PACKAGE_MANGLE_NAME( UTILS_MutexUnlock )
STATIC_INLINE void
UTILS_MutexUnlock( UTILS_Mutex* mutex );

/* Wait for a mutex state to be 'unlocked' */
#define UTILS_MutexWait PACKAGE_MANGLE_NAME( UTILS_MutexWait )
STATIC_INLINE void
UTILS_MutexWait( UTILS_Mutex*          mutex,
                 UTILS_Atomic_Memorder memorder );

UTILS_END_C_DECLS


#if HAVE( GCC_ATOMIC_BUILTINS )
#include "../src/mutex/UTILS_Mutex.inc.c"
#endif /* GCC_ATOMIC_BUILTINS */

#undef STATIC_INLINE

#endif /* UTILS_MUTEX_H */
