Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' into CRTP
[simgrid.git] / include / simgrid / s4u / Semaphore.hpp
1 /* Copyright (c) 2006-2019. 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  *  @ingroup s4u_api
17  *
18  * It is strictly impossible to use a real semaphore, such as
19  * <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_init.html">sem_init</a>,
20  * because it would block the whole simulation.
21  * Instead, you should use the present class, that offers a very similar interface.
22  *
23  * As for any S4U object, Semaphores are using the @ref s4u_raii "RAII idiom" for memory management.
24  * Use #create() to get a simgrid::s4u::SemaphorePtr to a newly created semaphore
25  * and only manipulate simgrid::s4u::SemaphorePtr.
26  *
27  */
28 class XBT_PUBLIC Semaphore {
29   smx_sem_t sem_;
30   std::atomic_int_fast32_t refcount_{0};
31
32   friend void intrusive_ptr_add_ref(Semaphore* sem);
33   friend void intrusive_ptr_release(Semaphore* sem);
34
35 public:
36   explicit Semaphore(unsigned int initial_capacity);
37   ~Semaphore();
38
39   // No copy:
40   /** You cannot create a new semaphore by copying an existing one. Use SemaphorePtr instead */
41   Semaphore(Semaphore const&) = delete;
42   /** You cannot create a new semaphore by value assignment either. Use SemaphorePtr instead */
43   Semaphore& operator=(Semaphore const&) = delete;
44
45   /** Constructs a new semaphore */
46   static SemaphorePtr create(unsigned int initial_capacity);
47
48   void acquire();
49   int acquire_timeout(double timeout);
50   void release();
51   int get_capacity();
52   int would_block();
53 };
54
55 } // namespace s4u
56 } // namespace simgrid
57
58 #endif /* SIMGRID_S4U_SEMAPHORE_HPP */