📄 mutex.c
字号:
#include <stdio.h>
#include <stdlib.h>
#if !defined(OS_WINDOWS)
#include <pthread.h>
#endif
#include "os.h"
#include "aplog.h"
#include "mutex.h"
struct mutex_hd {
#if !defined(OS_WINDOWS)
pthread_mutex_t mutex;
#else
HANDLE hMutex;
#endif
};
void *mutex_open(void *t)
{
struct mutex_hd *mhd;
if ((mhd = (struct mutex_hd *)malloc(sizeof(*mhd))) == NULL)
return NULL;
{
#if !defined(OS_WINDOWS)
pthread_mutex_init(&(mhd->mutex), NULL);
#else
SECURITY_ATTRIBUTES SecurityAttr;
char *name = (char *)t;
SecurityAttr.nLength = sizeof(SecurityAttr);
SecurityAttr.lpSecurityDescriptor = NULL;
SecurityAttr.bInheritHandle = TRUE;
hMutex = CreateMutex(&SecurityAttr, FALSE, name);
if(hMutex == NULL) {
LGWRERROR1(NULL, 0, "CreateMutex(%s) failed.", name);
free(mhd);
return;
}
#endif /* #if !defined(OS_WINDOWS) */
}
return mhd;
}
void mutex_close(void *hd)
{
struct mutex_hd *mhd = (struct mutex_hd *)hd;
if (!mhd)
return;
#if !defined(OS_WINDOWS)
pthread_mutex_destroy(&(mhd->mutex));
#else
CloseHandle(mhd->hMutex);
#endif /* #if !defined(OS_WINDOWS) */
free(mhd);
}
/* Return Value:
* If the specified action, lock or unlock, succeeded, the return
* value is zero. If an error occurred, the return value is non-zero.
*/
int mutex_lock(void *hd)
{
struct mutex_hd *mhd = (struct mutex_hd *)hd;
if (!mhd)
return -1;
#if !defined(OS_WINDOWS)
return pthread_mutex_lock(&(mhd->mutex));
#else
if(WAIT_OBJECT_0 == WaitForSingleObject(hMutex, INFINITE))
return(0);
LGWRERROR(NULL, 0, "FATAL: WaitForSingleObject(INFINITE) failed.");
return(-1);
#endif /* #if !defined(OS_WINDOWS) */
}
int mutex_unlock(void *hd)
{
struct mutex_hd *mhd = (struct mutex_hd *)hd;
if (!mhd)
return -1;
#if !defined(OS_WINDOWS)
return pthread_mutex_unlock(&(mhd->mutex));
#else
if(ReleaseMutex(mhd->hMutex))
return(0);
else {
LGWRERROR(NULL, 0, "ReleaseMutex failed.");
return(-1);
}
#endif /* #if !defined(OS_WINDOWS) */
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -