aboutsummaryrefslogtreecommitdiff
path: root/src/mutex.c
blob: 95514129a4c90380d94d3a2945f7fb05bda94ea7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
 *
 * mutex.c
 *
 * Cross platform mutex
 *
 */

#include "mutex.h"

int mutex_init(mutex_t *mutex)
{
#ifdef _WIN32
  *mutex = CreateMutex(NULL, FALSE, NULL);
  return (*mutex == NULL);
#else
  return pthread_mutex_init(mutex, NULL);;
#endif
}

int mutex_lock(mutex_t *mutex)
{
#ifdef _WIN32
  if (*mutex == NULL) { /* static initializer? */
    HANDLE p = CreateMutex(NULL, FALSE, NULL);
    if (InterlockedCompareExchangePointer((PVOID*)mutex, (PVOID)p, NULL) != NULL)
      CloseHandle(p);
  }
  return (WaitForSingleObject(*mutex, INFINITE) == WAIT_FAILED);
#else
  return pthread_mutex_lock(mutex);
#endif
}

int mutex_unlock(mutex_t *mutex)
{
#ifdef _WIN32
  return (ReleaseMutex(*mutex) == 0);
#else
  return pthread_mutex_unlock(mutex);
#endif
}

int mutex_cleanup(mutex_t *mutex)
{
#ifdef _WIN32
  return (CloseHandle(mutex) == 0);
#else
  return pthread_mutex_destroy(mutex);
#endif
}

/*
 * vim: set sw=2 sts=2 ts=8 et fdm=marker :
 */