1 /* Copyright (c) 2018-2021. The SimGrid Team. All rights reserved. */
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. */
6 #include "src/msg/msg_private.hpp"
9 #include "simgrid/forward.h"
10 #include "simgrid/s4u/Semaphore.hpp"
11 #include "src/kernel/activity/SemaphoreImpl.hpp"
16 Semaphore::Semaphore(unsigned int initial_capacity) : pimpl_(new kernel::activity::SemaphoreImpl(initial_capacity)) {}
18 Semaphore::~Semaphore()
20 if (pimpl_ != nullptr) {
21 xbt_assert(not pimpl_->is_used(), "Cannot destroy semaphore since someone is still using it");
26 SemaphorePtr Semaphore::create(unsigned int initial_capacity)
28 return SemaphorePtr(new Semaphore(initial_capacity));
31 void Semaphore::acquire()
33 simcall_sem_acquire(pimpl_);
36 int Semaphore::acquire_timeout(double timeout)
38 return simcall_sem_acquire_timeout(pimpl_, timeout);
41 void Semaphore::release()
43 kernel::actor::simcall([this] { pimpl_->release(); });
46 int Semaphore::get_capacity() const
48 return kernel::actor::simcall([this] { return pimpl_->get_capacity(); });
51 int Semaphore::would_block() const
53 return kernel::actor::simcall([this] { return pimpl_->would_block(); });
56 void intrusive_ptr_add_ref(Semaphore* sem)
59 sem->refcount_.fetch_add(1, std::memory_order_relaxed);
62 void intrusive_ptr_release(Semaphore* sem)
65 if (sem->refcount_.fetch_sub(1, std::memory_order_release) == 1) {
66 std::atomic_thread_fence(std::memory_order_acquire);
72 } // namespace simgrid
74 /* **************************** Public C interface *************************** */
75 /** @brief creates a semaphore object of the given initial capacity */
76 sg_sem_t sg_sem_init(int initial_value)
78 return new simgrid::s4u::Semaphore(initial_value);
81 /** @brief locks on a semaphore object */
82 void sg_sem_acquire(sg_sem_t sem)
87 /** @brief locks on a semaphore object up until the provided timeout expires */
88 int sg_sem_acquire_timeout(sg_sem_t sem, double timeout)
90 return sem->acquire_timeout(timeout);
93 /** @brief releases the semaphore object */
94 void sg_sem_release(sg_sem_t sem)
99 int sg_sem_get_capacity(const_sg_sem_t sem)
101 return sem->get_capacity();
104 void sg_sem_destroy(const_sg_sem_t sem)
109 /** @brief returns a boolean indicating if this semaphore would block at this very specific time
111 * Note that the returned value may be wrong right after the function call, when you try to use it...
112 * But that's a classical semaphore issue, and SimGrid's semaphore are not different to usual ones here.
114 int sg_sem_would_block(const_sg_sem_t sem)
116 return sem->would_block();