YARP
Yet Another Robot Platform
Event.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2006-2020 Istituto Italiano di Tecnologia (IIT)
3  * Copyright (C) 2006-2010 RobotCub Consortium
4  * All rights reserved.
5  *
6  * This software may be modified and distributed under the terms of the
7  * BSD-3-Clause license. See the accompanying LICENSE file for details.
8  */
9 
10 #include <yarp/os/Event.h>
11 #include <yarp/os/Semaphore.h>
12 
13 #include <mutex>
14 
16 {
17 public:
18  Private(bool autoReset) :
19  autoReset(autoReset),
20  action(0)
21  {
22  signalled = false;
23  waiters = 0;
24  }
25 
26  void wait()
27  {
28  stateMutex.lock();
29  if (signalled) {
30  stateMutex.unlock();
31  return;
32  }
33  waiters++;
34  stateMutex.unlock();
35  action.wait();
36  if (autoReset) {
37  reset();
38  }
39  }
40 
41  void signal(bool after = true)
42  {
43  stateMutex.lock();
44  int w = waiters;
45  if (w > 0) {
46  if (autoReset) {
47  w = 1;
48  }
49  for (int i = 0; i < w; i++) {
50  action.post();
51  waiters--;
52  }
53  }
54  signalled = after;
55  stateMutex.unlock();
56  }
57 
58  void reset()
59  {
60  stateMutex.lock();
61  signalled = false;
62  stateMutex.unlock();
63  }
64 
65 private:
66  bool autoReset;
67  bool signalled;
68  int waiters;
69  std::mutex stateMutex;
70  Semaphore action;
71 };
72 
73 
74 yarp::os::Event::Event(bool autoResetAfterWait) :
75  mPriv(new Private(autoResetAfterWait))
76 {
77 }
78 
80 {
81  delete mPriv;
82 }
83 
85 {
86  mPriv->wait();
87 }
88 
90 {
91  mPriv->signal();
92 }
93 
95 {
96  mPriv->reset();
97 }
yarp::os::Semaphore
A class for thread synchronization and mutual exclusion.
Definition: Semaphore.h:29
yarp::os::Event::Event
Event(bool autoResetAfterWait=true)
Constructor.
Definition: Event.cpp:74
yarp::os::Event::Private::Private
Private(bool autoReset)
Definition: Event.cpp:18
yarp::os::Event::signal
void signal()
Put the event in a signaled state.
Definition: Event.cpp:89
yarp::os::Event::Private::wait
void wait()
Definition: Event.cpp:26
yarp::os::Semaphore::wait
void wait()
Decrement the counter, even if we must wait to do that.
Definition: Semaphore.cpp:99
yarp::os::Event::wait
void wait()
Wait for the event to be signaled.
Definition: Event.cpp:84
yarp::os::Semaphore::post
void post()
Increment the counter.
Definition: Semaphore.cpp:114
yarp::os::Event::~Event
virtual ~Event()
Destructor.
Definition: Event.cpp:79
yarp::os::Event::reset
void reset()
Put the event in a reset state.
Definition: Event.cpp:94
yarp::os::Event::Private::signal
void signal(bool after=true)
Definition: Event.cpp:41
Event.h
Semaphore.h
yarp::os::Event::Private::reset
void reset()
Definition: Event.cpp:58
yarp::os::Event::Private
Definition: Event.cpp:16