1 /*
2  * libiio - Library for interfacing industrial I/O (IIO) devices
3  *
4  * Copyright (C) 2015 Analog Devices, Inc.
5  * Author: Paul Cercueil <paul.cercueil@analog.com>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  */
18 
19 #include "iio-config.h"
20 
21 #ifdef _WIN32
22 #include <windows.h>
23 #elif !defined(NO_THREADS)
24 #include <pthread.h>
25 #endif
26 
27 #include <stdlib.h>
28 
29 struct iio_mutex {
30 #ifdef NO_THREADS
31 	int foo; /* avoid complaints about empty structure */
32 #else
33 #ifdef _WIN32
34 	CRITICAL_SECTION lock;
35 #else
36 	pthread_mutex_t lock;
37 #endif
38 #endif
39 };
40 
iio_mutex_create(void)41 struct iio_mutex * iio_mutex_create(void)
42 {
43 	struct iio_mutex *lock = malloc(sizeof(*lock));
44 
45 	if (!lock)
46 		return NULL;
47 
48 #ifndef NO_THREADS
49 #ifdef _WIN32
50 	InitializeCriticalSection(&lock->lock);
51 #else
52 	pthread_mutex_init(&lock->lock, NULL);
53 #endif
54 #endif
55 	return lock;
56 }
57 
iio_mutex_destroy(struct iio_mutex * lock)58 void iio_mutex_destroy(struct iio_mutex *lock)
59 {
60 #ifndef NO_THREADS
61 #ifdef _WIN32
62 	DeleteCriticalSection(&lock->lock);
63 #else
64 	pthread_mutex_destroy(&lock->lock);
65 #endif
66 #endif
67 	free(lock);
68 }
69 
iio_mutex_lock(struct iio_mutex * lock)70 void iio_mutex_lock(struct iio_mutex *lock)
71 {
72 #ifndef NO_THREADS
73 #ifdef _WIN32
74 	EnterCriticalSection(&lock->lock);
75 #else
76 	pthread_mutex_lock(&lock->lock);
77 #endif
78 #endif
79 }
80 
iio_mutex_unlock(struct iio_mutex * lock)81 void iio_mutex_unlock(struct iio_mutex *lock)
82 {
83 #ifndef NO_THREADS
84 #ifdef _WIN32
85 	LeaveCriticalSection(&lock->lock);
86 #else
87 	pthread_mutex_unlock(&lock->lock);
88 #endif
89 #endif
90 }
91