Scroom 0.14-49-gb7ae7a6d
Loading...
Searching...
No Matches
semaphore.hh
Go to the documentation of this file.
1/*
2 * Scroom - Generic viewer for 2D data
3 * Copyright (C) 2009-2026 Kees-Jan Dijkzeul
4 *
5 * SPDX-License-Identifier: LGPL-2.1
6 */
7
8#pragma once
9
10#include <boost/date_time/posix_time/posix_time.hpp>
11#include <boost/thread.hpp>
12
13namespace Scroom
14{
16 {
17 private:
18 unsigned int count;
19 boost::condition_variable cond;
20 boost::mutex mut;
21
22 public:
23 explicit Semaphore(unsigned int count = 0);
24 void P();
25 void V();
26
27 template <typename duration_type>
28 bool P(duration_type const& rel_time);
29
30 bool try_P();
31 };
32
33 inline Semaphore::Semaphore(unsigned int count_)
34 : count(count_)
35 {
36 }
37
38 inline void Semaphore::P()
39 {
40 boost::mutex::scoped_lock lock(mut);
41 while(count == 0)
42 {
43 cond.wait(lock);
44 }
45 count--;
46 }
47
48 inline bool Semaphore::try_P()
49 {
50 boost::mutex::scoped_lock const lock(mut);
51 if(count > 0)
52 {
53 count--;
54 return true;
55 }
56
57 return false;
58 }
59
60 template <typename duration_type>
61 inline bool Semaphore::P(duration_type const& rel_time)
62 {
63 boost::posix_time::ptime const timeout = boost::posix_time::second_clock::universal_time() + rel_time;
64
65 boost::mutex::scoped_lock lock(mut);
66 while(count == 0)
67 {
68 if(!cond.timed_wait(lock, timeout))
69 {
70 return false;
71 }
72 }
73 count--;
74 return true;
75 }
76
77 inline void Semaphore::V()
78 {
79 boost::mutex::scoped_lock const lock(mut);
80 count++;
81 cond.notify_one();
82 }
83} // namespace Scroom
Definition semaphore.hh:16
boost::condition_variable cond
Definition semaphore.hh:19
boost::mutex mut
Definition semaphore.hh:20
unsigned int count
Definition semaphore.hh:18
void P()
Definition semaphore.hh:38
void V()
Definition semaphore.hh:77
Semaphore(unsigned int count=0)
Definition semaphore.hh:33
bool try_P()
Definition semaphore.hh:48
Definition blockallocator.hh:18
const size_t count
Definition pageprovider-tests.cc:21