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 SemaphorePtr Semaphore::create(unsigned int initial_capacity)
18 auto* sem = new kernel::activity::SemaphoreImpl(initial_capacity);
19 return SemaphorePtr(&sem->sem(), false);
22 void Semaphore::acquire()
24 simcall_sem_acquire(pimpl_);
27 bool Semaphore::acquire_timeout(double timeout)
29 return simcall_sem_acquire_timeout(pimpl_, timeout);
32 void Semaphore::release()
34 kernel::actor::simcall([this] { pimpl_->release(); });
37 int Semaphore::get_capacity() const
39 return kernel::actor::simcall([this] { return pimpl_->get_capacity(); });
42 bool Semaphore::would_block() const
44 return kernel::actor::simcall([this] { return pimpl_->would_block(); });
47 /* refcounting of the intrusive_ptr is delegated to the implementation object */
48 void intrusive_ptr_add_ref(const Semaphore* sem)
54 void intrusive_ptr_release(const Semaphore* sem)
61 } // namespace simgrid
63 /* **************************** Public C interface *************************** */
64 /** @brief creates a semaphore object of the given initial capacity */
65 sg_sem_t sg_sem_init(int initial_value)
67 return simgrid::s4u::Semaphore::create(initial_value).detach();
70 /** @brief locks on a semaphore object */
71 void sg_sem_acquire(sg_sem_t sem)
76 /** @brief locks on a semaphore object up until the provided timeout expires */
77 int sg_sem_acquire_timeout(sg_sem_t sem, double timeout)
79 return sem->acquire_timeout(timeout);
82 /** @brief releases the semaphore object */
83 void sg_sem_release(sg_sem_t sem)
88 int sg_sem_get_capacity(const_sg_sem_t sem)
90 return sem->get_capacity();
93 void sg_sem_destroy(const_sg_sem_t sem)
95 intrusive_ptr_release(sem);
98 /** @brief returns a boolean indicating if this semaphore would block at this very specific time
100 * Note that the returned value may be wrong right after the function call, when you try to use it...
101 * But that's a classical semaphore issue, and SimGrid's semaphore are not different to usual ones here.
103 int sg_sem_would_block(const_sg_sem_t sem)
105 return sem->would_block();