1 /* Copyright (c) 2018-2019. 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"
7 #include "src/simix/smx_synchro_private.hpp"
10 #include "simgrid/forward.h"
11 #include "simgrid/s4u/Semaphore.hpp"
16 Semaphore::Semaphore(unsigned int initial_capacity)
18 sem_ = simgrid::simix::simcall([initial_capacity] { return SIMIX_sem_init(initial_capacity); });
21 Semaphore::~Semaphore()
23 SIMIX_sem_destroy(sem_);
26 SemaphorePtr Semaphore::create(unsigned int initial_capacity)
28 return SemaphorePtr(new Semaphore(initial_capacity));
31 void Semaphore::acquire()
33 simcall_sem_acquire(sem_);
36 int Semaphore::acquire_timeout(double timeout)
38 return simcall_sem_acquire_timeout(sem_, timeout);
41 void Semaphore::release()
43 simgrid::simix::simcall([this] { SIMIX_sem_release(sem_); });
46 int Semaphore::get_capacity()
48 return simgrid::simix::simcall([this] { return SIMIX_sem_get_capacity(sem_); });
51 int Semaphore::would_block()
53 return simgrid::simix::simcall([this] { return SIMIX_sem_would_block(sem_); });
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);
73 /* **************************** Public C interface *************************** */
74 /** @brief creates a semaphore object of the given initial capacity */
75 sg_sem_t sg_sem_init(int initial_value)
77 return new simgrid::s4u::Semaphore(initial_value);
80 /** @brief locks on a semaphore object */
81 void sg_sem_acquire(sg_sem_t sem)
86 /** @brief locks on a semaphore object up until the provided timeout expires */
87 int sg_sem_acquire_timeout(sg_sem_t sem, double timeout)
89 return sem->acquire_timeout(timeout);
92 /** @brief releases the semaphore object */
93 void sg_sem_release(sg_sem_t sem)
98 int sg_sem_get_capacity(sg_sem_t sem)
100 return sem->get_capacity();
103 void sg_sem_destroy(sg_sem_t sem)
108 /** @brief returns a boolean indicating if this semaphore would block at this very specific time
110 * Note that the returned value may be wrong right after the function call, when you try to use it...
111 * But that's a classical semaphore issue, and SimGrid's semaphore are not different to usual ones here.
113 int sg_sem_would_block(sg_sem_t sem)
115 return sem->would_block();