ifw-fgf 1.0.0-pre1
Loading...
Searching...
No Matches
binarySemaphore.hpp
Go to the documentation of this file.
1
7/*
8 Copyright (c) 2016 Erik Rigtorp <erik@rigtorp.se>
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15 The above copyright notice and this permission notice shall be included in all
16 copies or substantial portions of the Software.
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 SOFTWARE.
24 */
25
26#pragma once
27
28#include <atomic>
29#include <cerrno>
30#include <exception>
31#include <linux/futex.h>
32#include <sys/syscall.h>
33#include <time.h>
34#include <unistd.h>
35
36namespace {
37 static int futex(int *uaddr, int futex_op, int val,
38 const struct timespec *timeout, int *uaddr2, int val3) {
39 return syscall(SYS_futex, uaddr, futex_op, val, timeout, uaddr2, val3);
40 }
41}
42
44
49 public:
50
51 bool wait(struct timespec *timeout = nullptr) {
52 for (;;) {
53 int one = 1;
54 if (i.compare_exchange_strong(one, 0, std::memory_order_relaxed,
55 std::memory_order_relaxed)) {
56 return true;
57 }
58 auto rc = futex((int *)&i, FUTEX_WAIT, 0, timeout, nullptr, 0);
59 if (rc == -1) {
60 if (errno == ETIMEDOUT) {
61 return false;
62 }
63 if (errno != EAGAIN) {
64 std::terminate();
65 }
66 }
67 }
68 }
69
70 void post() {
71 int zero = 0;
72 if (i.compare_exchange_strong(zero, 1, std::memory_order_relaxed,
73 std::memory_order_relaxed)) {
74 if (futex((int *)&i, FUTEX_WAKE, 1, nullptr, nullptr, 0) == -1) {
75 std::terminate();
76 }
77 }
78 }
79
80 private:
81 std::atomic<int> i = {0};
82 };
83}
Binary semaphore class to be used for thread synchronisation.
Definition binarySemaphore.hpp:48
bool wait(struct timespec *timeout=nullptr)
Definition binarySemaphore.hpp:51
void post()
Definition binarySemaphore.hpp:70
Frame Grabber Camera Base Class definitions.
Definition binarySemaphore.hpp:43