Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Activity refactoring
[simgrid.git] / src / kernel / activity / SemaphoreImpl.hpp
1 /* Copyright (c) 2019-2021. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #ifndef SIMGRID_KERNEL_ACTIVITY_SEMAPHOREIMPL_HPP
7 #define SIMGRID_KERNEL_ACTIVITY_SEMAPHOREIMPL_HPP
8
9 #include <atomic>
10 #include <boost/intrusive/list.hpp>
11
12 #include "simgrid/s4u/Semaphore.hpp"
13 #include "src/kernel/actor/ActorImpl.hpp"
14
15 namespace simgrid {
16 namespace kernel {
17 namespace activity {
18
19 class XBT_PUBLIC SemaphoreImpl {
20   std::atomic_int_fast32_t refcount_{1};
21   s4u::Semaphore piface_;
22   unsigned int value_;
23   actor::SynchroList sleeping_; /* list of sleeping actors*/
24
25 public:
26   explicit SemaphoreImpl(unsigned int value) : piface_(this), value_(value){};
27
28   SemaphoreImpl(SemaphoreImpl const&) = delete;
29   SemaphoreImpl& operator=(SemaphoreImpl const&) = delete;
30
31   void acquire(actor::ActorImpl* issuer, double timeout);
32   void release();
33   bool would_block() const { return (value_ == 0); }
34   void remove_sleeping_actor(actor::ActorImpl& actor) { xbt::intrusive_erase(sleeping_, actor); }
35
36   unsigned int get_capacity() const { return value_; }
37   bool is_used() const { return not sleeping_.empty(); }
38
39   SemaphoreImpl* ref();
40   void unref();
41
42   friend void intrusive_ptr_add_ref(SemaphoreImpl* sem)
43   {
44     XBT_ATTRIB_UNUSED auto previous = sem->refcount_.fetch_add(1);
45     xbt_assert(previous != 0);
46   }
47   friend void intrusive_ptr_release(SemaphoreImpl* sem)
48   {
49     if (sem->refcount_.fetch_sub(1) == 1) {
50       xbt_assert(not sem->is_used(), "Cannot destroy semaphore since someone is still using it");
51       delete sem;
52     }
53   }
54
55   s4u::Semaphore& sem() { return piface_; }
56 };
57 } // namespace activity
58 } // namespace kernel
59 } // namespace simgrid
60
61 #endif /* SIMGRID_KERNEL_ACTIVITY_SEMAPHOREIMPL_HPP */