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 xbt_assert(not pimpl_->is_used(), "Cannot destroy semaphore since someone is still using it");
24 SemaphorePtr Semaphore::create(unsigned int initial_capacity)
26 return SemaphorePtr(new Semaphore(initial_capacity));
29 void Semaphore::acquire()
31 simcall_sem_acquire(pimpl_);
34 int Semaphore::acquire_timeout(double timeout)
36 return simcall_sem_acquire_timeout(pimpl_, timeout);
39 void Semaphore::release()
41 kernel::actor::simcall([this] { pimpl_->release(); });
44 int Semaphore::get_capacity() const
46 return kernel::actor::simcall([this] { return pimpl_->get_capacity(); });
49 int Semaphore::would_block() const
51 return kernel::actor::simcall([this] { return pimpl_->would_block(); });
54 void intrusive_ptr_add_ref(Semaphore* sem)
57 sem->refcount_.fetch_add(1, std::memory_order_relaxed);
60 void intrusive_ptr_release(Semaphore* sem)
63 if (sem->refcount_.fetch_sub(1, std::memory_order_release) == 1) {
64 std::atomic_thread_fence(std::memory_order_acquire);
70 } // namespace simgrid
72 /* **************************** Public C interface *************************** */
73 /** @brief creates a semaphore object of the given initial capacity */
74 sg_sem_t sg_sem_init(int initial_value)
76 return new simgrid::s4u::Semaphore(initial_value);
79 /** @brief locks on a semaphore object */
80 void sg_sem_acquire(sg_sem_t sem)
85 /** @brief locks on a semaphore object up until the provided timeout expires */
86 int sg_sem_acquire_timeout(sg_sem_t sem, double timeout)
88 return sem->acquire_timeout(timeout);
91 /** @brief releases the semaphore object */
92 void sg_sem_release(sg_sem_t sem)
97 int sg_sem_get_capacity(const_sg_sem_t sem)
99 return sem->get_capacity();
102 void sg_sem_destroy(const_sg_sem_t sem)
107 /** @brief returns a boolean indicating if this semaphore would block at this very specific time
109 * Note that the returned value may be wrong right after the function call, when you try to use it...
110 * But that's a classical semaphore issue, and SimGrid's semaphore are not different to usual ones here.
112 int sg_sem_would_block(const_sg_sem_t sem)
114 return sem->would_block();