63 lines
1.8 KiB
C
63 lines
1.8 KiB
C
#include <c_Mutex.h>
|
|||
|
|
|
||
|
|
c_err_t c_Mutex_Init(c_Mutex_t* mutex) {
|
||
|
|
if (!mutex) return C_ERR_FAIL;
|
||
|
|
|
||
|
|
#if defined(PLATFORM_WINDOWS)
|
||
|
|
// InitializeCriticalSection 不会失败,但 InitializeCriticalSectionAndSpinCount 可能会
|
||
|
|
// 工业级推荐直接使用此 API,性能优秀
|
||
|
|
InitializeCriticalSection(&mutex->handle);
|
||
|
|
mutex->is_initialized = C_TRUE;
|
||
|
|
return C_ERR_OK;
|
||
|
|
#elif defined(PLATFORM_POSIX)
|
||
|
|
// POSIX 默认是 PTHREAD_MUTEX_DEFAULT (不可重入锁)
|
||
|
|
if (pthread_mutex_init(&mutex->handle, NULL) == 0) {
|
||
|
|
mutex->is_initialized = C_TRUE;
|
||
|
|
return C_ERR_SUCCESS;
|
||
|
|
}
|
||
|
|
return C_ERR_FAIL;
|
||
|
|
#endif
|
||
|
|
}
|
||
|
|
|
||
|
|
void c_Mutex_Destroy(c_Mutex_t* mutex) {
|
||
|
|
if (!mutex || !mutex->is_initialized) return;
|
||
|
|
|
||
|
|
#if defined(PLATFORM_WINDOWS)
|
||
|
|
DeleteCriticalSection(&mutex->handle);
|
||
|
|
#elif defined(PLATFORM_POSIX)
|
||
|
|
pthread_mutex_destroy(&mutex->handle);
|
||
|
|
#endif
|
||
|
|
mutex->is_initialized = C_FALSE;
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
void c_Mutex_Lock(c_Mutex_t* mutex) {
|
||
|
|
if (!mutex || !mutex->is_initialized) return;
|
||
|
|
#if defined(PLATFORM_WINDOWS)
|
||
|
|
EnterCriticalSection(&mutex->handle);
|
||
|
|
#elif defined(PLATFORM_POSIX)
|
||
|
|
pthread_mutex_lock(&mutex->handle);
|
||
|
|
#endif
|
||
|
|
}
|
||
|
|
|
||
|
|
c_bool_t c_Mutex_TryLock(c_Mutex_t* mutex) {
|
||
|
|
if (!mutex || !mutex->is_initialized) return C_FALSE;
|
||
|
|
|
||
|
|
#if defined(PLATFORM_WINDOWS)
|
||
|
|
// TryEnterCriticalSection 返回非 0 表示成功
|
||
|
|
return (TryEnterCriticalSection(&mutex->handle) != 0)?C_TRUE:C_FALSE;
|
||
|
|
#elif defined(PLATFORM_POSIX)
|
||
|
|
// pthread_mutex_trylock 返回 0 表示成功
|
||
|
|
return (pthread_mutex_trylock(&mutex->handle) == 0)?C_TRUE:C_FALSE;
|
||
|
|
#endif
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
void c_Mutex_UnLock(c_Mutex_t* mutex) {
|
||
|
|
if (!mutex || !mutex->is_initialized) return;
|
||
|
|
#if defined(PLATFORM_WINDOWS)
|
||
|
|
LeaveCriticalSection(&mutex->handle);
|
||
|
|
#elif defined(PLATFORM_POSIX)
|
||
|
|
pthread_mutex_unlock(&mutex->handle);
|
||
|
|
#endif
|
||
|
|
}
|