Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of https://framagit.org/simgrid/simgrid
[simgrid.git] / include / simgrid / s4u / Semaphore.hpp
1 /* Copyright (c) 2006-2023. 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_S4U_SEMAPHORE_HPP
7 #define SIMGRID_S4U_SEMAPHORE_HPP
8
9 #include <simgrid/forward.h>
10
11 namespace simgrid::s4u {
12
13 /** @brief A classical semaphore, but blocking in the simulation world
14  *
15  * @beginrst
16  * It is strictly impossible to use a real semaphore, such as
17  * `sem_init <http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_init.html>`_,
18  * because it would block the whole simulation.
19  * Instead, you should use the present class, that offers a very similar interface.
20  *
21  * An example is available in Section :ref:`s4u_ex_IPC`.
22  *
23  * As for any S4U object, you can use the :ref:`RAII idiom <s4u_raii>` for memory management of semaphores.
24  * Use :cpp:func:`create() <simgrid::s4u::Mutex::create()>` to get a :cpp:type:`simgrid::s4u::SemaphorePtr` to a newly
25  * created semaphore, that will get automatically freed when the variable goes out of scope.
26  * @endrst
27  *
28  */
29 class XBT_PUBLIC Semaphore {
30 #ifndef DOXYGEN
31   friend kernel::activity::SemaphoreImpl;
32   friend XBT_PUBLIC void kernel::activity::intrusive_ptr_release(kernel::activity::SemaphoreImpl* sem);
33 #endif
34
35   kernel::activity::SemaphoreImpl* const pimpl_;
36
37   friend XBT_PUBLIC void intrusive_ptr_add_ref(const Semaphore* sem);
38   friend XBT_PUBLIC void intrusive_ptr_release(const Semaphore* sem);
39
40   explicit Semaphore(kernel::activity::SemaphoreImpl* sem) : pimpl_(sem) {}
41   ~Semaphore() = default;
42 #ifndef DOXYGEN
43   Semaphore(Semaphore const&) = delete;            // No copy constructor. Use SemaphorePtr instead
44   Semaphore& operator=(Semaphore const&) = delete; // No direct assignment either. Use SemaphorePtr instead
45 #endif
46
47 public:
48   /** \static Constructs a new semaphore */
49   static SemaphorePtr create(unsigned int initial_capacity);
50
51   void acquire();
52   /** Returns true if there was a timeout */
53   bool acquire_timeout(double timeout);
54   void release();
55   int get_capacity() const;
56   bool would_block() const;
57 };
58
59 } // namespace simgrid::s4u
60
61 #endif /* SIMGRID_S4U_SEMAPHORE_HPP */