Merge branch 'master' of 10.3.0.4:public/netxms
[public/netxms.git] / src / libstrophe / thread.c
1 /* thread.c
2 ** strophe XMPP client library -- thread abstraction
3 **
4 ** Copyright (C) 2005-2009 Collecta, Inc.
5 **
6 ** This software is provided AS-IS with no warranty, either express
7 ** or implied.
8 **
9 ** This software is distributed under license and may not be copied,
10 ** modified or distributed except as expressly authorized under the
11 ** terms of the license contained in the file LICENSE.txt in this
12 ** distribution.
13 */
14
15 /** @file
16 * Thread absraction.
17 */
18
19 #include <nms_common.h>
20 #include <strophe.h>
21 #include "common.h"
22 #include "thread.h"
23
24 struct _mutex_t {
25 const xmpp_ctx_t *ctx;
26
27 #ifdef _WIN32
28 HANDLE mutex;
29 #else
30 pthread_mutex_t *mutex;
31 #endif
32 };
33
34 /* mutex functions */
35
36 mutex_t *mutex_create(const xmpp_ctx_t * ctx)
37 {
38 mutex_t *mutex;
39
40 mutex = xmpp_alloc(ctx, sizeof(mutex_t));
41 if (mutex) {
42 mutex->ctx = ctx;
43 #ifdef _WIN32
44 mutex->mutex = CreateMutex(NULL, FALSE, NULL);
45 #else
46 mutex->mutex = xmpp_alloc(ctx, sizeof(pthread_mutex_t));
47 if (mutex->mutex)
48 if (pthread_mutex_init(mutex->mutex, NULL) != 0) {
49 xmpp_free(ctx, mutex->mutex);
50 mutex->mutex = NULL;
51 }
52 #endif
53 if (!mutex->mutex) {
54 xmpp_free(ctx, mutex);
55 mutex = NULL;
56 }
57 }
58
59 return mutex;
60 }
61
62 int mutex_destroy(mutex_t *mutex)
63 {
64 int ret = 1;
65 const xmpp_ctx_t *ctx;
66
67 #ifdef _WIN32
68 if (mutex->mutex)
69 ret = CloseHandle(mutex->mutex);
70 #else
71 if (mutex->mutex)
72 ret = pthread_mutex_destroy(mutex->mutex) == 0;
73 #endif
74 ctx = mutex->ctx;
75 xmpp_free(ctx, mutex);
76
77 return ret;
78 }
79
80 int mutex_lock(mutex_t *mutex)
81 {
82 int ret;
83
84 #ifdef _WIN32
85 ret = WaitForSingleObject(mutex->mutex, INFINITE) == 0;
86 #else
87 ret = pthread_mutex_lock(mutex->mutex) == 0;
88 #endif
89
90 return ret;
91 }
92
93 int mutex_trylock(mutex_t *mutex)
94 {
95 /* TODO */
96 return 0;
97 }
98
99 int mutex_unlock(mutex_t *mutex)
100 {
101 int ret;
102
103 #ifdef _WIN32
104 ret = ReleaseMutex(mutex->mutex);
105 #else
106 ret = pthread_mutex_unlock(mutex->mutex) == 0;
107 #endif
108
109 return ret;
110 }