summaryrefslogtreecommitdiff
path: root/src/libstrongswan/threading/windows/semaphore.c
blob: 29f523d3ea9074d0e0a6e8796ce6d1da2119c0c7 (plain)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
 * Copyright (C) 2013 Martin Willi
 * Copyright (C) 2013 revosec AG
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.  See <http://www.fsf.org/copyleft/gpl.txt>.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 */

#include <library.h>
#include <threading/semaphore.h>

typedef struct private_semaphore_t private_semaphore_t;

/**
 * private data of a semaphore
 */
struct private_semaphore_t {
	/**
	 * public interface
	 */
	semaphore_t public;

	/**
	 * Handle to semaphore
	 */
	HANDLE handle;
};

METHOD(semaphore_t, timed_wait, bool,
	private_semaphore_t *this, u_int timeout)
{
	/* use alertable wait to allow cancellation */
	return WaitForSingleObjectEx(this->handle, timeout, TRUE) == WAIT_TIMEOUT;
}

METHOD(semaphore_t, timed_wait_abs, bool,
	private_semaphore_t *this, timeval_t tv)
{
	DWORD timeout;
	timeval_t now, diff;

	time_monotonic(&now);
	if (timercmp(&now, &tv, >))
	{
		return TRUE;
	}
	timersub(&tv, &now, &diff);
	timeout = diff.tv_sec * 1000 + diff.tv_usec / 1000;

	return timed_wait(this, timeout);
}

METHOD(semaphore_t, wait_, void,
	private_semaphore_t *this)
{
	timed_wait(this, INFINITE);
}

METHOD(semaphore_t, post, void,
	private_semaphore_t *this)
{
	ReleaseSemaphore(this->handle, 1, NULL);
}

METHOD(semaphore_t, destroy, void,
	private_semaphore_t *this)
{
	CloseHandle(this->handle);
	free(this);
}

/*
 * Described in header
 */
semaphore_t *semaphore_create(u_int value)
{
	private_semaphore_t *this;

	INIT(this,
		.public = {
			.wait = _wait_,
			.timed_wait = _timed_wait,
			.timed_wait_abs = _timed_wait_abs,
			.post = _post,
			.destroy = _destroy,
		},
		/* our API does not have an upper limit, but Windows requires one.
		 * 0xFFFFFFF (268435455) is the highest value for which Windows does
		 * not return ERROR_INVALID_PARAMETER, and should be sufficient. */
		.handle = CreateSemaphore(NULL, value, 0xFFFFFFF, NULL),
	);

	return &this->public;
}