Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines.
[simgrid.git] / include / simgrid / s4u / Semaphore.hpp
1 /* Copyright (c) 2006-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_S4U_SEMAPHORE_HPP
7 #define SIMGRID_S4U_SEMAPHORE_HPP
8
9 #include <simgrid/forward.h>
10 #include <simgrid/simix.h>
11
12 namespace simgrid {
13 namespace s4u {
14
15 /** @brief A classical semaphore, but blocking in the simulation world
16  *
17  * @rst
18  * It is strictly impossible to use a real semaphore, such as
19  * `sem_init <http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_init.html>`_,
20  * because it would block the whole simulation.
21  * Instead, you should use the present class, that offers a very similar interface.
22  *
23  * An example is available in Section :ref:`s4u_ex_IPC`.
24  *
25  * As for any S4U object, you can use the :ref:`RAII idiom <s4u_raii>` for memory management of semaphores.
26  * Use :cpp:func:`create() <simgrid::s4u::Mutex::create()>` to get a :cpp:type:`simgrid::s4u::SemaphorePtr` to a newly
27  * created semaphore, that will get automatically freed when the variable goes out of scope.
28  * @endrst
29  *
30  */
31 class XBT_PUBLIC Semaphore {
32   smx_sem_t sem_;
33   std::atomic_int_fast32_t refcount_{0};
34
35   friend void intrusive_ptr_add_ref(Semaphore* sem);
36   friend void intrusive_ptr_release(Semaphore* sem);
37
38 public:
39   explicit Semaphore(unsigned int initial_capacity);
40   ~Semaphore();
41
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   /** Constructs a new semaphore */
48   static SemaphorePtr create(unsigned int initial_capacity);
49
50   void acquire();
51   int acquire_timeout(double timeout);
52   void release();
53   int get_capacity() const;
54   int would_block() const;
55 };
56
57 } // namespace s4u
58 } // namespace simgrid
59
60 #endif /* SIMGRID_S4U_SEMAPHORE_HPP */