Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'dev-get-hostname-faster' into 'master'
[simgrid.git] / src / bindings / python / simgrid_python.cpp
1 /* Copyright (c) 2018-2022. 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 #ifdef _WIN32
7 #warning Try to work around https://bugs.python.org/issue11566
8 #define _hypot hypot
9 #endif
10
11 #if defined(__GNUG__)
12 #pragma GCC diagnostic push
13 #pragma GCC diagnostic ignored "-Wunused-value"
14 #endif
15
16 #include <pybind11/pybind11.h> // Must come before our own stuff
17
18 #include <pybind11/functional.h>
19 #include <pybind11/stl.h>
20
21 #if defined(__GNUG__)
22 #pragma GCC diagnostic pop
23 #endif
24
25 #include "simgrid/kernel/ProfileBuilder.hpp"
26 #include "simgrid/kernel/routing/NetPoint.hpp"
27 #include <simgrid/Exception.hpp>
28 #include <simgrid/s4u/Actor.hpp>
29 #include <simgrid/s4u/Barrier.hpp>
30 #include <simgrid/s4u/Comm.hpp>
31 #include <simgrid/s4u/Disk.hpp>
32 #include <simgrid/s4u/Engine.hpp>
33 #include <simgrid/s4u/Exec.hpp>
34 #include <simgrid/s4u/Host.hpp>
35 #include <simgrid/s4u/Link.hpp>
36 #include <simgrid/s4u/Mailbox.hpp>
37 #include <simgrid/s4u/Mutex.hpp>
38 #include <simgrid/s4u/NetZone.hpp>
39 #include <simgrid/s4u/Semaphore.hpp>
40 #include <simgrid/version.h>
41
42 #include <algorithm>
43 #include <memory>
44 #include <string>
45 #include <vector>
46
47 namespace py = pybind11;
48 using simgrid::s4u::Actor;
49 using simgrid::s4u::ActorPtr;
50 using simgrid::s4u::Barrier;
51 using simgrid::s4u::BarrierPtr;
52 using simgrid::s4u::Comm;
53 using simgrid::s4u::CommPtr;
54 using simgrid::s4u::Engine;
55 using simgrid::s4u::Host;
56 using simgrid::s4u::Link;
57 using simgrid::s4u::Mailbox;
58 using simgrid::s4u::Mutex;
59 using simgrid::s4u::MutexPtr;
60 using simgrid::s4u::Semaphore;
61 using simgrid::s4u::SemaphorePtr;
62
63 XBT_LOG_NEW_DEFAULT_CATEGORY(python, "python");
64
65 namespace {
66
67 std::string get_simgrid_version()
68 {
69   int major;
70   int minor;
71   int patch;
72   sg_version_get(&major, &minor, &patch);
73   return simgrid::xbt::string_printf("%i.%i.%i", major, minor, patch);
74 }
75
76 /** @brief Wrap for mailbox::get_async */
77 class PyGetAsync {
78   std::unique_ptr<PyObject*> data = std::make_unique<PyObject*>();
79
80 public:
81   PyObject** get() const { return data.get(); }
82 };
83
84 } // namespace
85
86 PYBIND11_DECLARE_HOLDER_TYPE(T, boost::intrusive_ptr<T>)
87
88 PYBIND11_MODULE(simgrid, m)
89 {
90   m.doc() = "SimGrid userspace API";
91
92   m.attr("simgrid_version") = get_simgrid_version();
93
94   // Swapped contexts are broken, starting from pybind11 v2.8.0.  Use thread contexts by default.
95   simgrid::s4u::Engine::set_config("contexts/factory:thread");
96
97   // Internal exception used to kill actors and sweep the RAII chimney (free objects living on the stack)
98   static py::object pyForcefulKillEx(py::register_exception<simgrid::ForcefulKillException>(m, "ActorKilled"));
99
100   py::register_exception<simgrid::NetworkFailureException>(m, "NetworkFailureException");
101   py::register_exception<simgrid::TimeoutException>(m, "TimeoutException");
102   py::register_exception<simgrid::HostFailureException>(m, "HostFailureException");
103   py::register_exception<simgrid::StorageFailureException>(m, "StorageFailureException");
104   py::register_exception<simgrid::VmFailureException>(m, "VmFailureException");
105   py::register_exception<simgrid::CancelException>(m, "CancelException");
106   py::register_exception<simgrid::AssertionError>(m, "AssertionError");
107
108   /* this_actor namespace */
109   m.def_submodule("this_actor", "Bindings of the s4u::this_actor namespace. See the C++ documentation for details.")
110       .def(
111           "debug", [](const char* s) { XBT_DEBUG("%s", s); }, "Display a logging message of 'debug' priority.")
112       .def(
113           "info", [](const char* s) { XBT_INFO("%s", s); }, "Display a logging message of 'info' priority.")
114       .def(
115           "warning", [](const char* s) { XBT_WARN("%s", s); }, "Display a logging message of 'warning' priority.")
116       .def(
117           "error", [](const char* s) { XBT_ERROR("%s", s); }, "Display a logging message of 'error' priority.")
118       .def("execute", py::overload_cast<double, double>(&simgrid::s4u::this_actor::execute),
119            py::call_guard<py::gil_scoped_release>(),
120            "Block the current actor, computing the given amount of flops at the given priority.", py::arg("flops"),
121            py::arg("priority") = 1)
122       .def("exec_init", py::overload_cast<double>(&simgrid::s4u::this_actor::exec_init),
123            py::call_guard<py::gil_scoped_release>())
124       .def("exec_async", py::overload_cast<double>(&simgrid::s4u::this_actor::exec_async),
125            py::call_guard<py::gil_scoped_release>())
126       .def("parallel_execute", &simgrid::s4u::this_actor::parallel_execute,
127            py::call_guard<py::gil_scoped_release>(),
128            "Run a parallel task (requires the 'ptask_L07' model)")
129       .def("exec_init",
130            py::overload_cast<const std::vector<simgrid::s4u::Host*>&, const std::vector<double>&,
131            const std::vector<double>&>  (&simgrid::s4u::this_actor::exec_init),
132            py::call_guard<py::gil_scoped_release>(),
133            "Initiate a parallel task (requires the 'ptask_L07' model)")
134       .def("get_host", &simgrid::s4u::this_actor::get_host, "Retrieves host on which the current actor is located")
135       .def("set_host", &simgrid::s4u::this_actor::set_host, py::call_guard<py::gil_scoped_release>(),
136            "Moves the current actor to another host.", py::arg("dest"))
137       .def("sleep_for", static_cast<void (*)(double)>(&simgrid::s4u::this_actor::sleep_for),
138            py::call_guard<py::gil_scoped_release>(), "Block the actor sleeping for that amount of seconds.",
139            py::arg("duration"))
140       .def("sleep_until", static_cast<void (*)(double)>(&simgrid::s4u::this_actor::sleep_until),
141            py::call_guard<py::gil_scoped_release>(), "Block the actor sleeping until the specified timestamp.",
142            py::arg("duration"))
143       .def("suspend", &simgrid::s4u::this_actor::suspend, py::call_guard<py::gil_scoped_release>(),
144            "Suspend the current actor, that is blocked until resume()ed by another actor.")
145       .def("yield_", &simgrid::s4u::this_actor::yield, py::call_guard<py::gil_scoped_release>(), "Yield the actor")
146       .def("exit", &simgrid::s4u::this_actor::exit, py::call_guard<py::gil_scoped_release>(), "kill the current actor")
147       .def(
148           "on_exit",
149           [](py::object cb) {
150             py::function fun = py::reinterpret_borrow<py::function>(cb);
151             fun.inc_ref(); // FIXME: why is this needed for tests like actor-kill and actor-lifetime?
152             simgrid::s4u::this_actor::on_exit([fun](bool failed) {
153               py::gil_scoped_acquire py_context; // need a new context for callback
154               try {
155                 fun(failed);
156               } catch (const py::error_already_set& e) {
157                 xbt_die("Error while executing the on_exit lambda: %s", e.what());
158               }
159             });
160           },
161           py::call_guard<py::gil_scoped_release>(),
162           "Define a lambda to be called when the actor ends. It takes a bool parameter indicating whether the actor "
163           "was killed. If False, the actor finished peacefully.")
164       .def("get_pid", &simgrid::s4u::this_actor::get_pid, "Retrieves PID of the current actor")
165       .def("get_ppid", &simgrid::s4u::this_actor::get_ppid,
166            "Retrieves PPID of the current actor (i.e., the PID of its parent).");
167
168   /* Class Engine */
169   py::class_<Engine>(m, "Engine", "Simulation Engine")
170       .def(py::init([](std::vector<std::string> args) {
171              auto argc = static_cast<int>(args.size());
172              std::vector<char*> argv(args.size() + 1); // argv[argc] is nullptr
173              std::transform(begin(args), end(args), begin(argv), [](std::string& s) { return &s.front(); });
174              // Currently this can be dangling, we should wrap this somehow.
175              return new simgrid::s4u::Engine(&argc, argv.data());
176            }),
177            "The constructor should take the parameters from the command line, as is ")
178       .def_static("get_clock",
179                   []() // XBT_ATTRIB_DEPRECATED_v334
180                   {
181                     PyErr_WarnEx(
182                         PyExc_DeprecationWarning,
183                         "get_clock() is deprecated and  will be dropped after v3.33, use `Engine.clock` instead.", 1);
184                     return Engine::get_clock();
185                   })
186       .def_property_readonly_static(
187           "clock", [](py::object /* self */) { return Engine::get_clock(); },
188           "The simulation time, ie the amount of simulated seconds since the simulation start.")
189       .def_property_readonly_static(
190           "instance", [](py::object /* self */) { return Engine::get_instance(); }, "Retrieve the simulation engine")
191       .def("get_all_hosts",
192            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
193            {
194              PyErr_WarnEx(PyExc_DeprecationWarning,
195                           "get_all_hosts() is deprecated and  will be dropped after v3.33, use all_hosts instead.", 1);
196              return self.attr("all_hosts");
197            })
198       .def("host_by_name", &Engine::host_by_name_or_null, py::call_guard<py::gil_scoped_release>(),
199            "Retrieve a host by its name, or None if it does not exist in the platform.")
200       .def_property_readonly("all_hosts", &Engine::get_all_hosts, "Returns the list of all hosts found in the platform")
201       .def("get_all_links",
202            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
203            {
204              PyErr_WarnEx(PyExc_DeprecationWarning,
205                           "get_all_links() is deprecated and  will be dropped after v3.33, use all_links instead.", 1);
206              return self.attr("all_links");
207            })
208       .def_property_readonly("all_links", &Engine::get_all_links, "Returns the list of all links found in the platform")
209       .def("get_all_netpoints",
210            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
211            {
212              PyErr_WarnEx(
213                  PyExc_DeprecationWarning,
214                  "get_all_netpoints() is deprecated and  will be dropped after v3.33, use all_netpoints instead.", 1);
215              return self.attr("all_netpoints");
216            })
217       .def_property_readonly("all_netpoints", &Engine::get_all_netpoints)
218       .def("get_netzone_root",
219            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
220            {
221              PyErr_WarnEx(PyExc_DeprecationWarning,
222                           "get_netzone_root() is deprecated and  will be dropped after v3.3, use netzone_root instead.",
223                           1);
224              return self.attr("netzone_root");
225            })
226       .def_property_readonly("netzone_root", &Engine::get_netzone_root,
227                              "Retrieve the root netzone, containing all others.")
228       .def("netpoint_by_name", &Engine::netpoint_by_name_or_null)
229       .def("netzone_by_name", &Engine::netzone_by_name_or_null)
230       .def("set_config", py::overload_cast<const std::string&>(&Engine::set_config),
231            "Change one of SimGrid's configurations")
232       .def("load_platform", &Engine::load_platform, "Load a platform file describing the environment")
233       .def("load_deployment", &Engine::load_deployment, "Load a deployment file and launch the actors that it contains")
234       .def("mailbox_by_name_or_create", &Engine::mailbox_by_name_or_create,
235            py::call_guard<py::gil_scoped_release>(),
236            py::arg("name"),
237            "Find a mailbox from its name or create one if it does not exist")
238       .def("run", &Engine::run, py::call_guard<py::gil_scoped_release>(), "Run the simulation until its end")
239       .def("run_until", py::overload_cast<double>(&Engine::run_until, py::const_),
240            py::call_guard<py::gil_scoped_release>(), "Run the simulation until the given date",
241            py::arg("max_date") = -1)
242       .def(
243           "register_actor",
244           [](Engine* e, const std::string& name, py::object fun_or_class) {
245             e->register_actor(name, [fun_or_class](std::vector<std::string> args) {
246               py::gil_scoped_acquire py_context;
247               try {
248                 /* Convert the std::vector into a py::tuple */
249                 py::tuple params(args.size() - 1);
250                 for (size_t i = 1; i < args.size(); i++)
251                   params[i - 1] = py::cast(args[i]);
252
253                 py::object res = fun_or_class(*params);
254                 /* If I was passed a class, I just built an instance, so I need to call it now */
255                 if (py::isinstance<py::function>(res))
256                   res();
257               } catch (const py::error_already_set& ex) {
258                 if (ex.matches(pyForcefulKillEx)) {
259                   XBT_VERB("Actor killed");
260                   simgrid::ForcefulKillException::do_throw(); // Forward that ForcefulKill exception
261                 }
262                 throw;
263               }
264             });
265           },
266           "Registers the main function of an actor");
267
268   /* Class Netzone */
269   py::class_<simgrid::s4u::NetZone, std::unique_ptr<simgrid::s4u::NetZone, py::nodelete>> netzone(
270       m, "NetZone", "Networking Zones. See the C++ documentation for details.");
271   netzone.def_static("create_full_zone", &simgrid::s4u::create_full_zone, "Creates a zone of type FullZone")
272       .def_static("create_torus_zone", &simgrid::s4u::create_torus_zone, "Creates a cluster of type Torus")
273       .def_static("create_fatTree_zone", &simgrid::s4u::create_fatTree_zone, "Creates a cluster of type Fat-Tree")
274       .def_static("create_dragonfly_zone", &simgrid::s4u::create_dragonfly_zone, "Creates a cluster of type Dragonfly")
275       .def_static("create_star_zone", &simgrid::s4u::create_star_zone, "Creates a zone of type Star")
276       .def_static("create_floyd_zone", &simgrid::s4u::create_floyd_zone, "Creates a zone of type Floyd")
277       .def_static("create_dijkstra_zone", &simgrid::s4u::create_floyd_zone, "Creates a zone of type Dijkstra")
278       .def_static("create_vivaldi_zone", &simgrid::s4u::create_vivaldi_zone, "Creates a zone of type Vivaldi")
279       .def_static("create_empty_zone", &simgrid::s4u::create_empty_zone, "Creates a zone of type Empty")
280       .def_static("create_wifi_zone", &simgrid::s4u::create_wifi_zone, "Creates a zone of type Wi-Fi")
281       .def("add_route",
282            py::overload_cast<simgrid::kernel::routing::NetPoint*, simgrid::kernel::routing::NetPoint*,
283                              simgrid::kernel::routing::NetPoint*, simgrid::kernel::routing::NetPoint*,
284                              const std::vector<simgrid::s4u::LinkInRoute>&, bool>(&simgrid::s4u::NetZone::add_route),
285            "Add a route between 2 netpoints")
286       .def("create_host", py::overload_cast<const std::string&, double>(&simgrid::s4u::NetZone::create_host),
287            "Creates a host")
288       .def("create_host",
289            py::overload_cast<const std::string&, const std::string&>(&simgrid::s4u::NetZone::create_host),
290            "Creates a host")
291       .def("create_host",
292            py::overload_cast<const std::string&, const std::vector<double>&>(&simgrid::s4u::NetZone::create_host),
293            "Creates a host")
294       .def("create_host",
295            py::overload_cast<const std::string&, const std::vector<std::string>&>(&simgrid::s4u::NetZone::create_host),
296            "Creates a host")
297       .def("create_link", py::overload_cast<const std::string&, double>(&simgrid::s4u::NetZone::create_link),
298            "Creates a network link")
299       .def("create_link",
300            py::overload_cast<const std::string&, const std::string&>(&simgrid::s4u::NetZone::create_link),
301            "Creates a network link")
302       .def("create_link",
303            py::overload_cast<const std::string&, const std::vector<double>&>(&simgrid::s4u::NetZone::create_link),
304            "Creates a network link")
305       .def("create_link",
306            py::overload_cast<const std::string&, const std::vector<std::string>&>(&simgrid::s4u::NetZone::create_link),
307            "Creates a network link")
308       .def("create_split_duplex_link",
309            py::overload_cast<const std::string&, double>(&simgrid::s4u::NetZone::create_split_duplex_link),
310            "Creates a split-duplex link")
311       .def("create_split_duplex_link",
312            py::overload_cast<const std::string&, const std::string&>(&simgrid::s4u::NetZone::create_split_duplex_link),
313            "Creates a split-duplex link")
314       .def("create_router", &simgrid::s4u::NetZone::create_router, "Create a router")
315       .def("set_parent", &simgrid::s4u::NetZone::set_parent, "Set the parent of this zone")
316       .def("set_property", &simgrid::s4u::NetZone::set_property, "Add a property to this zone")
317       .def("get_netpoint",
318            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
319            {
320              PyErr_WarnEx(PyExc_DeprecationWarning,
321                           "get_netpoint() is deprecated and  will be dropped after v3.33, use netpoint instead.", 1);
322              return self.attr("netpoint");
323            })
324       .def_property_readonly("netpoint", &simgrid::s4u::NetZone::get_netpoint,
325                              "Retrieve the netpoint associated to this zone")
326       .def("seal", &simgrid::s4u::NetZone::seal, "Seal this NetZone")
327       .def_property_readonly(
328           "name", [](const simgrid::s4u::NetZone* self) { return self->get_name(); },
329           "The name of this network zone (read-only property).");
330
331   /* Class ClusterCallbacks */
332   py::class_<simgrid::s4u::ClusterCallbacks>(m, "ClusterCallbacks", "Callbacks used to create cluster zones")
333       .def(py::init<const std::function<simgrid::s4u::ClusterCallbacks::ClusterNetPointCb>&,
334                     const std::function<simgrid::s4u::ClusterCallbacks::ClusterLinkCb>&,
335                     const std::function<simgrid::s4u::ClusterCallbacks::ClusterLinkCb>&>());
336
337   /* Class FatTreeParams */
338   py::class_<simgrid::s4u::FatTreeParams>(m, "FatTreeParams", "Parameters to create a Fat-Tree zone")
339       .def(py::init<unsigned int, const std::vector<unsigned int>&, const std::vector<unsigned int>&,
340                     const std::vector<unsigned int>&>());
341
342   /* Class DragonflyParams */
343   py::class_<simgrid::s4u::DragonflyParams>(m, "DragonflyParams", "Parameters to create a Dragonfly zone")
344       .def(py::init<const std::pair<unsigned int, unsigned int>&, const std::pair<unsigned int, unsigned int>&,
345                     const std::pair<unsigned int, unsigned int>&, unsigned int>());
346
347   /* Class Host */
348   py::class_<simgrid::s4u::Host, std::unique_ptr<Host, py::nodelete>> host(
349       m, "Host", "Simulated host. See the C++ documentation for details.");
350   host.def_static("by_name", &Host::by_name, py::arg("name"), "Retrieves a host from its name, or die")
351       .def(
352           "route_to",
353           [](const simgrid::s4u::Host* h, const simgrid::s4u::Host* to) {
354             auto* list = new std::vector<Link*>();
355             double bw  = 0;
356             h->route_to(to, *list, &bw);
357             return make_tuple(list, bw);
358           },
359           "Retrieves the list of links and the bandwidth between two hosts.")
360       .def(
361           "set_speed_profile",
362           [](Host* h, const std::string& profile, double period) {
363             h->set_speed_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
364           },
365           py::call_guard<py::gil_scoped_release>(),
366           "Specify a profile modeling the external load according to an exhaustive list. "
367           "Each line of the profile describes timed events as ``date ratio``. "
368           "For example, the following content describes an host which computational speed is initially 1 (i.e, 100%) "
369           "and then halved after 42 seconds:\n\n"
370           ".. code-block:: python\n\n"
371           "   \"\"\"\n"
372           "   0 1.0\n"
373           "   42 0.5\n"
374           "   \"\"\"\n\n"
375           ".. warning:: Don't get fooled: bandwidth and latency profiles of links contain absolute values,"
376           " while speed profiles of hosts contain ratios.\n\n"
377           "The second function parameter is the periodicity: the time to wait after the last event to start again over "
378           "the list. Set it to -1 to not loop over.")
379       .def(
380           "set_state_profile",
381           [](Host* h, const std::string& profile, double period) {
382             h->set_state_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
383           },
384           py::call_guard<py::gil_scoped_release>(),
385           "Specify a profile modeling the churn. "
386           "Each line of the profile describes timed events as ``date boolean``, where the boolean (0 or 1) tells "
387           "whether the host is on. "
388           "For example, the following content describes a link which turns off at t=1 and back on at t=2:\n\n"
389           ".. code-block:: python\n\n"
390           "   \"\"\"\n"
391           "   1.0 0\n"
392           "   2.0 1\n"
393           "   \"\"\"\n\n"
394           "The second function parameter is the periodicity: the time to wait after the last event to start again over "
395           "the list. Set it to -1 to not loop over.")
396       .def("get_pstate_count",
397            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
398            {
399              PyErr_WarnEx(
400                  PyExc_DeprecationWarning,
401                  "get_pstate_count() is deprecated and  will be dropped after v3.33, use pstate_count instead.", 1);
402              return self.attr("pstate_count");
403            })
404       .def_property_readonly("pstate_count", &Host::get_pstate_count, "Retrieve the count of defined pstate levels")
405       .def("get_pstate_speed",
406            [](py::object self, int state) // XBT_ATTRIB_DEPRECATED_v334
407            {
408              PyErr_WarnEx(
409                  PyExc_DeprecationWarning,
410                  "get_pstate_speed() is deprecated and  will be dropped after v3.33, use pstate_speed instead.", 1);
411              return self.attr("pstate_speed")(state);
412            })
413       .def("pstate_speed", &Host::get_pstate_speed, py::call_guard<py::gil_scoped_release>(),
414            "Retrieve the maximal speed at the given pstate")
415       .def("get_netpoint",
416            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
417            {
418              PyErr_WarnEx(PyExc_DeprecationWarning,
419                           "get_netpoint() is deprecated and  will be dropped after v3.33, use netpoint instead.", 1);
420              return self.attr("netpoint");
421            })
422       .def_property_readonly("netpoint", &Host::get_netpoint, "Retrieve the netpoint associated to this zone")
423       .def("get_disks", &Host::get_disks, "Retrieve the list of disks in this host")
424       .def("set_core_count",
425            [](py::object self, double count) // XBT_ATTRIB_DEPRECATED_v334
426            {
427              PyErr_WarnEx(PyExc_DeprecationWarning,
428                           "set_core_count() is deprecated and  will be dropped after v3.33, use core_count instead.",
429                           1);
430              self.attr("core_count")(count);
431            })
432       .def_property(
433           "core_count", &Host::get_core_count,
434           [](Host* h, int count) {
435             py::gil_scoped_release gil_guard;
436             return h->set_core_count(count);
437           },
438           "Manage the number of cores in the CPU")
439       .def("set_coordinates", &Host::set_coordinates, py::call_guard<py::gil_scoped_release>(),
440            "Set the coordinates of this host")
441       .def("set_sharing_policy", &simgrid::s4u::Host::set_sharing_policy, py::call_guard<py::gil_scoped_release>(),
442            "Describe how the CPU is shared", py::arg("policy"), py::arg("cb") = simgrid::s4u::NonLinearResourceCb())
443       .def("create_disk", py::overload_cast<const std::string&, double, double>(&Host::create_disk),
444            py::call_guard<py::gil_scoped_release>(), "Create a disk")
445       .def("create_disk",
446            py::overload_cast<const std::string&, const std::string&, const std::string&>(&Host::create_disk),
447            py::call_guard<py::gil_scoped_release>(), "Create a disk")
448       .def("seal", &Host::seal, py::call_guard<py::gil_scoped_release>(), "Seal this host")
449       .def_property(
450           "pstate", &Host::get_pstate,
451           [](Host* h, int i) {
452             py::gil_scoped_release gil_guard;
453             h->set_pstate(i);
454           },
455           "The current pstate (read/write property).")
456       .def_static("current", &Host::current, py::call_guard<py::gil_scoped_release>(),
457            "Retrieves the host on which the running actor is located.")
458       .def_property_readonly(
459           "name",
460           [](const Host* self) {
461             return std::string(self->get_name().c_str()); // Convert from xbt::string because of MC
462           },
463           "The name of this host (read-only property).")
464       .def_property_readonly("load", &Host::get_load,
465                              "Returns the current computation load (in flops per second), NOT taking the external load "
466                              "into account. This is the currently achieved speed (read-only property).")
467       .def_property_readonly(
468           "speed", &Host::get_speed,
469           "The peak computing speed in flops/s at the current pstate, NOT taking the external load into account. "
470           "This is the max potential speed (read-only property).")
471       .def_property_readonly("available_speed", &Host::get_available_speed,
472                              "Get the available speed ratio, between 0 and 1.\n"
473                              "This accounts for external load (see :py:func:`set_speed_profile() "
474                              "<simgrid.Host.set_speed_profile>`) (read-only property).")
475       .def_static(
476           "on_creation_cb",
477           [](py::object cb) {
478             Host::on_creation_cb([cb](Host& h) {
479               py::function fun = py::reinterpret_borrow<py::function>(cb);
480               py::gil_scoped_acquire py_context; // need a new context for callback
481               try {
482                 fun(&h);
483               } catch (const py::error_already_set& e) {
484                 xbt_die("Error while executing the on_creation lambda : %s", e.what());
485               }
486             });
487           },
488           py::call_guard<py::gil_scoped_release>(), "");
489
490   py::enum_<simgrid::s4u::Host::SharingPolicy>(host, "SharingPolicy")
491       .value("NONLINEAR", simgrid::s4u::Host::SharingPolicy::NONLINEAR)
492       .value("LINEAR", simgrid::s4u::Host::SharingPolicy::LINEAR)
493       .export_values();
494
495   /* Class Disk */
496   py::class_<simgrid::s4u::Disk, std::unique_ptr<simgrid::s4u::Disk, py::nodelete>> disk(
497       m, "Disk", "Simulated disk. See the C++ documentation for details.");
498   disk.def("read", py::overload_cast<sg_size_t, double>(&simgrid::s4u::Disk::read, py::const_),
499            py::call_guard<py::gil_scoped_release>(), "Read data from disk", py::arg("size"), py::arg("priority") = 1)
500       .def("write", py::overload_cast<sg_size_t, double>(&simgrid::s4u::Disk::write, py::const_),
501            py::call_guard<py::gil_scoped_release>(), "Write data in disk", py::arg("size"), py::arg("priority") = 1)
502       .def("read_async", &simgrid::s4u::Disk::read_async, py::call_guard<py::gil_scoped_release>(),
503            "Non-blocking read data from disk")
504       .def("write_async", &simgrid::s4u::Disk::write_async, py::call_guard<py::gil_scoped_release>(),
505            "Non-blocking write data in disk")
506       .def("set_sharing_policy", &simgrid::s4u::Disk::set_sharing_policy, py::call_guard<py::gil_scoped_release>(),
507            "Set sharing policy for this disk", py::arg("op"), py::arg("policy"),
508            py::arg("cb") = simgrid::s4u::NonLinearResourceCb())
509       .def("seal", &simgrid::s4u::Disk::seal, py::call_guard<py::gil_scoped_release>(), "Seal this disk")
510       .def_property_readonly(
511           "name", [](const simgrid::s4u::Disk* self) { return self->get_name(); },
512           "The name of this disk (read-only property).");
513   py::enum_<simgrid::s4u::Disk::SharingPolicy>(disk, "SharingPolicy")
514       .value("NONLINEAR", simgrid::s4u::Disk::SharingPolicy::NONLINEAR)
515       .value("LINEAR", simgrid::s4u::Disk::SharingPolicy::LINEAR)
516       .export_values();
517   py::enum_<simgrid::s4u::Disk::Operation>(disk, "Operation")
518       .value("READ", simgrid::s4u::Disk::Operation::READ)
519       .value("WRITE", simgrid::s4u::Disk::Operation::WRITE)
520       .value("READWRITE", simgrid::s4u::Disk::Operation::READWRITE)
521       .export_values();
522
523   /* Class NetPoint */
524   py::class_<simgrid::kernel::routing::NetPoint, std::unique_ptr<simgrid::kernel::routing::NetPoint, py::nodelete>>
525       netpoint(m, "NetPoint", "NetPoint object");
526
527   /* Class Link */
528   py::class_<Link, std::unique_ptr<Link, py::nodelete>> link(m, "Link",
529                                                              "Network link. See the C++ documentation for details.");
530   link.def("set_latency", py::overload_cast<const std::string&>(&Link::set_latency),
531            py::call_guard<py::gil_scoped_release>(),
532            "Set the latency as a string. Accepts values with units, such as â€˜1s’ or â€˜7ms’.\nFull list of accepted "
533            "units: w (week), d (day), h, s, ms, us, ns, ps.")
534       .def("set_latency", py::overload_cast<double>(&Link::set_latency), py::call_guard<py::gil_scoped_release>(),
535            "Set the latency as a float (in seconds).")
536       .def("set_bandwidth", &Link::set_bandwidth, py::call_guard<py::gil_scoped_release>(),
537            "Set the bandwidth (in byte per second).")
538       .def(
539           "set_bandwidth_profile",
540           [](Link* l, const std::string& profile, double period) {
541             l->set_bandwidth_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
542           },
543           py::call_guard<py::gil_scoped_release>(),
544           "Specify a profile modeling the external load according to an exhaustive list. "
545           "Each line of the profile describes timed events as ``date bandwidth`` (in bytes per second). "
546           "For example, the following content describes a link which bandwidth changes to 40 Mb/s at t=4, and to 6 "
547           "Mb/s at t=8:\n\n"
548           ".. code-block:: python\n\n"
549           "   \"\"\"\n"
550           "   4.0 40000000\n"
551           "   8.0 60000000\n"
552           "   \"\"\"\n\n"
553           ".. warning:: Don't get fooled: bandwidth and latency profiles of links contain absolute values,"
554           " while speed profiles of hosts contain ratios.\n\n"
555           "The second function parameter is the periodicity: the time to wait after the last event to start again over "
556           "the list. Set it to -1 to not loop over.")
557       .def(
558           "set_latency_profile",
559           [](Link* l, const std::string& profile, double period) {
560             l->set_latency_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
561           },
562           py::call_guard<py::gil_scoped_release>(),
563           "Specify a profile modeling the external load according to an exhaustive list. "
564           "Each line of the profile describes timed events as ``date latency`` (in seconds). "
565           "For example, the following content describes a link which latency changes to 1ms (0.001s) at t=1, and to 2s "
566           "at t=2:\n\n"
567           ".. code-block:: python\n\n"
568           "   \"\"\"\n"
569           "   1.0 0.001\n"
570           "   2.0 2\n"
571           "   \"\"\"\n\n"
572           ".. warning:: Don't get fooled: bandwidth and latency profiles of links contain absolute values,"
573           " while speed profiles of hosts contain ratios.\n\n"
574           "The second function parameter is the periodicity: the time to wait after the last event to start again over "
575           "the list. Set it to -1 to not loop over.")
576       .def(
577           "set_state_profile",
578           [](Link* l, const std::string& profile, double period) {
579             l->set_state_profile(simgrid::kernel::profile::ProfileBuilder::from_string("", profile, period));
580           },
581           "Specify a profile modeling the churn. "
582           "Each line of the profile describes timed events as ``date boolean``, where the boolean (0 or 1) tells "
583           "whether the link is on. "
584           "For example, the following content describes a link which turns off at t=1 and back on at t=2:\n\n"
585           ".. code-block:: python\n\n"
586           "   \"\"\"\n"
587           "   1.0 0\n"
588           "   2.0 1\n"
589           "   \"\"\"\n\n"
590           "The second function parameter is the periodicity: the time to wait after the last event to start again over "
591           "the list. Set it to -1 to not loop over.")
592
593       .def("turn_on", &Link::turn_on, py::call_guard<py::gil_scoped_release>(), "Turns the link on.")
594       .def("turn_off", &Link::turn_off, py::call_guard<py::gil_scoped_release>(), "Turns the link off.")
595       .def("is_on", &Link::is_on, "Check whether the link is on.")
596
597       .def("set_sharing_policy", &Link::set_sharing_policy, py::call_guard<py::gil_scoped_release>(),
598            "Set sharing policy for this link")
599       .def("set_concurrency_limit", &Link::set_concurrency_limit, py::call_guard<py::gil_scoped_release>(),
600            "Set concurrency limit for this link")
601       .def("set_host_wifi_rate", &Link::set_host_wifi_rate, py::call_guard<py::gil_scoped_release>(),
602            "Set level of communication speed of given host on this Wi-Fi link")
603       .def_static("by_name", &Link::by_name, "Retrieves a Link from its name, or dies")
604       .def("seal", &Link::seal, py::call_guard<py::gil_scoped_release>(), "Seal this link")
605       .def_property_readonly(
606           "name",
607           [](const Link* self) {
608             return std::string(self->get_name().c_str()); // Convert from xbt::string because of MC
609           },
610           "The name of this link")
611       .def_property_readonly("bandwidth", &Link::get_bandwidth,
612                              "The bandwidth (in bytes per second) (read-only property).")
613       .def_property_readonly("latency", &Link::get_latency, "The latency (in seconds) (read-only property).");
614
615   py::enum_<Link::SharingPolicy>(link, "SharingPolicy")
616       .value("NONLINEAR", Link::SharingPolicy::NONLINEAR)
617       .value("WIFI", Link::SharingPolicy::WIFI)
618       .value("SPLITDUPLEX", Link::SharingPolicy::SPLITDUPLEX)
619       .value("SHARED", Link::SharingPolicy::SHARED)
620       .value("FATPIPE", Link::SharingPolicy::FATPIPE)
621       .export_values();
622
623   /* Class LinkInRoute */
624   py::class_<simgrid::s4u::LinkInRoute> linkinroute(m, "LinkInRoute", "Abstraction to add link in routes");
625   linkinroute.def(py::init<const Link*>());
626   linkinroute.def(py::init<const Link*, simgrid::s4u::LinkInRoute::Direction>());
627   py::enum_<simgrid::s4u::LinkInRoute::Direction>(linkinroute, "Direction")
628       .value("UP", simgrid::s4u::LinkInRoute::Direction::UP)
629       .value("DOWN", simgrid::s4u::LinkInRoute::Direction::DOWN)
630       .value("NONE", simgrid::s4u::LinkInRoute::Direction::NONE)
631       .export_values();
632
633   /* Class Split-Duplex Link */
634   py::class_<simgrid::s4u::SplitDuplexLink, Link, std::unique_ptr<simgrid::s4u::SplitDuplexLink, py::nodelete>>(
635       m, "SplitDuplexLink", "Network split-duplex link")
636       .def("get_link_up",
637            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
638            {
639              PyErr_WarnEx(PyExc_DeprecationWarning,
640                           "get_link_up() is deprecated and  will be dropped after v3.33, use link_up instead.", 1);
641              return self.attr("link_up");
642            })
643       .def_property_readonly("link_up", &simgrid::s4u::SplitDuplexLink::get_link_up, "Get link direction up")
644       .def("get_link_down",
645            [](py::object self) // XBT_ATTRIB_DEPRECATED_v334
646            {
647              PyErr_WarnEx(PyExc_DeprecationWarning,
648                           "get_link_down() is deprecated and  will be dropped after v3.33, use link_down instead.", 1);
649              return self.attr("link_down");
650            })
651       .def_property_readonly("link_down", &simgrid::s4u::SplitDuplexLink::get_link_down, "Get link direction down");
652
653   /* Class Mailbox */
654   py::class_<simgrid::s4u::Mailbox, std::unique_ptr<Mailbox, py::nodelete>>(
655       m, "Mailbox", "Mailbox. See the C++ documentation for details.")
656       .def(
657           "__str__", [](const Mailbox* self) { return std::string("Mailbox(") + self->get_cname() + ")"; },
658           "Textual representation of the Mailbox`")
659       .def_static("by_name", &Mailbox::by_name,
660                   py::call_guard<py::gil_scoped_release>(),
661                   py::arg("name"),
662                   "Retrieve a Mailbox from its name")
663       .def_property_readonly(
664           "name",
665           [](const Mailbox* self) {
666             return std::string(self->get_name().c_str()); // Convert from xbt::string because of MC
667           },
668           "The name of that mailbox (read-only property).")
669       .def_property_readonly("ready", &Mailbox::ready, py::call_guard<py::gil_scoped_release>(),
670                              "Check if there is a communication ready to be consumed from a mailbox.")
671       .def(
672           "put",
673           [](Mailbox* self, py::object data, uint64_t size, double timeout) {
674             data.inc_ref();
675             self->put(data.ptr(), size, timeout);
676           },
677           py::call_guard<py::gil_scoped_release>(), "Blocking data transmission with a timeout")
678       .def(
679           "put",
680           [](Mailbox* self, py::object data, uint64_t size) {
681             data.inc_ref();
682             self->put(data.ptr(), size);
683           },
684           py::call_guard<py::gil_scoped_release>(), "Blocking data transmission")
685       .def(
686           "put_async",
687           [](Mailbox* self, py::object data, uint64_t size) {
688             data.inc_ref();
689             return self->put_async(data.ptr(), size);
690           },
691           py::call_guard<py::gil_scoped_release>(), "Non-blocking data transmission")
692       .def(
693           "put_init",
694           [](Mailbox* self, py::object data, uint64_t size) {
695             data.inc_ref();
696             return self->put_init(data.ptr(), size);
697           },
698           py::call_guard<py::gil_scoped_release>(),
699           "Creates (but don’t start) a data transmission to that mailbox.")
700       .def(
701           "get",
702           [](Mailbox* self) {
703             py::object data = py::reinterpret_steal<py::object>(self->get<PyObject>());
704             // data.dec_ref(); // FIXME: why does it break python-actor-create?
705             return data;
706           },
707           py::call_guard<py::gil_scoped_release>(), "Blocking data reception")
708       .def(
709           "get_async",
710           [](Mailbox* self) -> std::tuple<CommPtr, PyGetAsync> {
711             PyGetAsync wrap;
712             auto comm = self->get_async(wrap.get());
713             return std::make_tuple(std::move(comm), std::move(wrap));
714           },
715           py::call_guard<py::gil_scoped_release>(),
716           "Non-blocking data reception. Use data.get() to get the python object after the communication has finished")
717       .def(
718           "set_receiver", [](Mailbox* self, ActorPtr actor) { self->set_receiver(actor); },
719           py::call_guard<py::gil_scoped_release>(), "Sets the actor as permanent receiver");
720
721   /* Class PyGetAsync */
722   py::class_<PyGetAsync>(m, "PyGetAsync", "Wrapper for async get communications")
723       .def(py::init<>())
724       .def(
725           "get", [](const PyGetAsync* self) { return py::reinterpret_steal<py::object>(*(self->get())); },
726           "Get python object after async communication in receiver side");
727
728   /* Class Comm */
729   py::class_<Comm, CommPtr>(m, "Comm", "Communication. See the C++ documentation for details.")
730       .def_property_readonly("dst_data_size", &Comm::get_dst_data_size,
731                              py::call_guard<py::gil_scoped_release>(),
732                              "Retrieve the size of the received data.")
733       .def_property_readonly("mailbox", &Comm::get_mailbox,
734                              py::call_guard<py::gil_scoped_release>(),
735                              "Retrieve the mailbox on which this comm acts.")
736       .def_property_readonly("sender", &Comm::get_sender,
737                              py::call_guard<py::gil_scoped_release>())
738       .def_property_readonly("state_str", [](const Comm* self){ return std::string(self->get_state_str()); },
739                              py::call_guard<py::gil_scoped_release>(),
740                              "Retrieve the Comm state as string")
741       .def_property_readonly("remaining",  &Comm::get_remaining,
742                              py::call_guard<py::gil_scoped_release>(),
743                              "Remaining amount of work that this Comm entails")
744       .def_property_readonly("start_time",  &Comm::get_start_time,
745                              py::call_guard<py::gil_scoped_release>(),
746                              "Time at which this Comm started")
747       .def_property_readonly("finish_time",  &Comm::get_finish_time,
748                              py::call_guard<py::gil_scoped_release>(),
749                              "Time at which this Comm finished")
750       .def("set_payload_size", &Comm::set_payload_size, py::call_guard<py::gil_scoped_release>(),
751            py::arg("bytes"),
752            "Specify the amount of bytes which exchange should be simulated.")
753       .def("set_rate", &Comm::set_rate, py::call_guard<py::gil_scoped_release>(),
754            py::arg("rate"),
755            "Sets the maximal communication rate (in byte/sec). Must be done before start")
756       .def("cancel", [](Comm* self){ return self->cancel(); },
757            py::call_guard<py::gil_scoped_release>(), py::return_value_policy::reference_internal,
758            "Cancel the activity.")
759       .def("start", [](Comm* self){ return self->start(); },
760            py::call_guard<py::gil_scoped_release>(), py::return_value_policy::reference_internal,
761            "Starts a previously created activity. This function is optional: you can call wait() even if you didn't "
762            "call start()")
763       .def("suspend", [](Comm* self){ return self->suspend(); },
764           py::call_guard<py::gil_scoped_release>(), py::return_value_policy::reference_internal,
765           "Suspend the activity.")
766       .def("resume", [](Comm* self){ return self->resume(); },
767           py::call_guard<py::gil_scoped_release>(), py::return_value_policy::reference_internal,
768           "Resume the activity.")
769       .def("test", &Comm::test, py::call_guard<py::gil_scoped_release>(),
770            "Test whether the communication is terminated.")
771       .def("wait", &Comm::wait, py::call_guard<py::gil_scoped_release>(),
772            "Block until the completion of that communication.")
773       .def("wait_for", &Comm::wait_for, py::call_guard<py::gil_scoped_release>(),
774            py::arg("timeout"),
775            "Block until the completion of that communication, or raises TimeoutException after the specified timeout.")
776       .def("wait_until", &Comm::wait_until, py::call_guard<py::gil_scoped_release>(),
777            py::arg("time_limit"),
778            "Block until the completion of that communication, or raises TimeoutException after the specified time.")
779       .def("detach", [](Comm* self) { return self->detach(); },
780            py::return_value_policy::reference_internal,
781            py::call_guard<py::gil_scoped_release>(),
782            "Start the comm, and ignore its result. It can be completely forgotten after that.")
783       .def_static("sendto", &Comm::sendto, py::call_guard<py::gil_scoped_release>(),
784                   py::arg("from"), py::arg("to"), py::arg("simulated_size_in_bytes"),
785                   "Do a blocking communication between two arbitrary hosts.")
786       .def_static("sendto_init", py::overload_cast<Host*, Host*>(&Comm::sendto_init),
787                   py::call_guard<py::gil_scoped_release>(),
788                   py::arg("from"), py::arg("to"),
789                   "Creates a communication between the two given hosts, bypassing the mailbox mechanism.")
790       .def_static("sendto_async", &Comm::sendto_async, py::call_guard<py::gil_scoped_release>(),
791                   py::arg("from"), py::arg("to"), py::arg("simulated_size_in_bytes"),
792                   "Do a blocking communication between two arbitrary hosts.\n\nThis initializes a communication that "
793                   "completely bypass the mailbox and actors mechanism. There is really no limit on the hosts involved. "
794                   "In particular, the actor does not have to be on one of the involved hosts.")
795       .def_static("test_any", &Comm::test_any,
796                   py::call_guard<py::gil_scoped_release>(),
797                   py::arg("comms"),
798                   "take a vector s4u::CommPtr and return the rank of the first finished one (or -1 if none is done)")
799       .def_static("wait_all", &Comm::wait_all, py::call_guard<py::gil_scoped_release>(),
800                   py::arg("comms"),
801                   "Block until the completion of all communications in the list.")
802       .def_static("wait_all_for", &Comm::wait_all_for, py::call_guard<py::gil_scoped_release>(),
803                   py::arg("comms"), py::arg("timeout"),
804                   "Block until the completion of all communications in the list, or raises TimeoutException after "
805                   "the specified timeout.")
806       .def_static("wait_any", &Comm::wait_any,
807                   py::call_guard<py::gil_scoped_release>(),
808                   py::arg("comms"),
809                   "Block until the completion of any communication in the list and return the index of the "
810                   "terminated one.")
811       .def_static("wait_any_for", &Comm::wait_any_for,
812                   py::call_guard<py::gil_scoped_release>(),
813                   py::arg("comms"), py::arg("timeout"),
814                   "Block until the completion of any communication in the list and return the index of the terminated "
815                   "one, or -1 if a timeout occurred.");
816
817   /* Class Io */
818   py::class_<simgrid::s4u::Io, simgrid::s4u::IoPtr>(m, "Io", "I/O activities. See the C++ documentation for details.")
819       .def("test", &simgrid::s4u::Io::test, py::call_guard<py::gil_scoped_release>(),
820            "Test whether the I/O is terminated.")
821       .def("wait", &simgrid::s4u::Io::wait, py::call_guard<py::gil_scoped_release>(),
822            "Block until the completion of that I/O operation")
823       .def_static(
824           "wait_any_for", &simgrid::s4u::Io::wait_any_for, py::call_guard<py::gil_scoped_release>(),
825           "Block until the completion of any I/O in the list (or timeout) and return the index of the terminated one.")
826       .def_static("wait_any", &simgrid::s4u::Io::wait_any, py::call_guard<py::gil_scoped_release>(),
827                   "Block until the completion of any I/O in the list and return the index of the terminated one.");
828
829   /* Class Exec */
830   py::class_<simgrid::s4u::Exec, simgrid::s4u::ExecPtr>(m, "Exec", "Execution. See the C++ documentation for details.")
831       .def_property_readonly(
832           "remaining",
833           [](simgrid::s4u::ExecPtr self) {
834             py::gil_scoped_release gil_guard;
835             return self->get_remaining();
836           },
837           "Amount of flops that remain to be computed until completion (read-only property).")
838       .def_property_readonly(
839           "remaining_ratio",
840           [](simgrid::s4u::ExecPtr self) {
841             py::gil_scoped_release gil_guard;
842             return self->get_remaining_ratio();
843           },
844           "Amount of work remaining until completion from 0 (completely done) to 1 (nothing done "
845           "yet) (read-only property).")
846       .def_property("host", &simgrid::s4u::Exec::get_host, &simgrid::s4u::Exec::set_host,
847                     "Host on which this execution runs. Only the first host is returned for parallel executions. "
848                     "Changing this value migrates the execution.")
849       .def("test", &simgrid::s4u::Exec::test, py::call_guard<py::gil_scoped_release>(),
850            "Test whether the execution is terminated.")
851       .def("cancel", &simgrid::s4u::Exec::cancel, py::call_guard<py::gil_scoped_release>(), "Cancel that execution.")
852       .def("start", &simgrid::s4u::Exec::start, py::call_guard<py::gil_scoped_release>(), "Start that execution.")
853       .def("suspend", &simgrid::s4u::Exec::suspend, py::call_guard<py::gil_scoped_release>(), "Suspend that execution.")
854       .def("wait", &simgrid::s4u::Exec::wait, py::call_guard<py::gil_scoped_release>(),
855            "Block until the completion of that execution.")
856       .def("wait_for", &simgrid::s4u::Exec::wait_for, py::call_guard<py::gil_scoped_release>(),
857            py::arg("timeout"),
858            "Block until the completion of that activity, or raises TimeoutException after the specified timeout.");
859
860   /* Class Semaphore */
861   py::class_<Semaphore, SemaphorePtr>(m, "Semaphore",
862                                       "A classical semaphore, but blocking in the simulation world. See the C++ "
863                                       "documentation for details.")
864       .def(py::init<>(&Semaphore::create), py::call_guard<py::gil_scoped_release>(), py::arg("capacity"),
865            "Semaphore constructor.")
866       .def("acquire", &Semaphore::acquire, py::call_guard<py::gil_scoped_release>(),
867            "Acquire on the semaphore object with no timeout. Blocks until the semaphore is acquired.")
868       .def("acquire_timeout", &Semaphore::acquire_timeout, py::call_guard<py::gil_scoped_release>(), py::arg("timeout"),
869            "Acquire on the semaphore object with no timeout. Blocks until the semaphore is acquired or return "
870            "true if it has not been acquired after the specified timeout.")
871       .def("release", &Semaphore::release, py::call_guard<py::gil_scoped_release>(),
872            "Release the semaphore.")
873       .def_property_readonly("capacity", &Semaphore::get_capacity, py::call_guard<py::gil_scoped_release>(),
874                              "Get the semaphore capacity.")
875       .def_property_readonly("would_block", &Semaphore::would_block, py::call_guard<py::gil_scoped_release>(),
876                              "Check whether trying to acquire the semaphore would block (in other word, checks whether "
877                              "this semaphore has capacity).")
878       // Allow semaphores to be automatically acquired/released with a context manager: `with semaphore: ...`
879       .def("__enter__", [](Semaphore* self){ self->acquire(); }, py::call_guard<py::gil_scoped_release>())
880       .def("__exit__", [](Semaphore* self){ self->release(); }, py::call_guard<py::gil_scoped_release>());
881
882   /* Class Mutex */
883   py::class_<Mutex, MutexPtr>(m, "Mutex",
884                               "A classical mutex, but blocking in the simulation world."
885                               "See the C++ documentation for details.")
886       .def(py::init<>(&Mutex::create), py::call_guard<py::gil_scoped_release>(), "Mutex constructor.")
887       .def("lock", &Mutex::lock, py::call_guard<py::gil_scoped_release>(), "Block until the mutex is acquired.")
888       .def("try_lock", &Mutex::try_lock, py::call_guard<py::gil_scoped_release>(),
889            "Try to acquire the mutex. Return true if the mutex was acquired, false otherwise.")
890       .def("unlock", &Mutex::unlock, py::call_guard<py::gil_scoped_release>(), "Release the mutex.")
891       // Allow mutexes to be automatically acquired/released with a context manager: `with mutex: ...`
892       .def("__enter__", [](Mutex* self){ self->lock(); }, py::call_guard<py::gil_scoped_release>())
893       .def("__exit__", [](Mutex* self, const py::object&, const py::object&, const py::object&) { self->unlock(); },
894           py::call_guard<py::gil_scoped_release>());
895
896   /* Class Barrier */
897   py::class_<Barrier, BarrierPtr>(m, "Barrier",
898                                   "A classical barrier, but blocking in the simulation world.")
899       .def(py::init<>(&Barrier::create), py::call_guard<py::gil_scoped_release>(), py::arg("expected_actors"),
900            "Barrier constructor.")
901       .def("wait", &Barrier::wait, py::call_guard<py::gil_scoped_release>(),
902            "Blocks into the barrier. Every waiting actors will be unlocked once the expected amount of actors reaches "
903            "the barrier.");
904
905   /* Class Actor */
906   py::class_<simgrid::s4u::Actor, ActorPtr>(m, "Actor",
907                                             "An actor is an independent stream of execution in your distributed "
908                                             "application. See the C++ documentation for details.")
909       .def(
910           "create",
911           [](py::str name, Host* h, py::object fun, py::args args) {
912             fun.inc_ref();  // FIXME: why is this needed for tests like exec-async, exec-dvfs and exec-remote?
913             args.inc_ref(); // FIXME: why is this needed for tests like actor-migrate?
914             return simgrid::s4u::Actor::create(name, h, [fun, args]() {
915               py::gil_scoped_acquire py_context;
916               try {
917                 fun(*args);
918               } catch (const py::error_already_set& ex) {
919                 if (ex.matches(pyForcefulKillEx)) {
920                   XBT_VERB("Actor killed");
921                   simgrid::ForcefulKillException::do_throw(); // Forward that ForcefulKill exception
922                 }
923                 throw;
924               }
925             });
926           },
927           py::call_guard<py::gil_scoped_release>(),
928           "Create an actor from a function or an object. See the :ref:`example <s4u_ex_actors_create>`.")
929       .def_property(
930           "host", &Actor::get_host,
931           [](Actor* a, Host* h) {
932             py::gil_scoped_release gil_guard;
933             a->set_host(h);
934           },
935           "The host on which this actor is located. Changing this value migrates the actor.\n\n"
936           "If the actor is currently blocked on an execution activity, the activity is also migrated to the new host. "
937           "If it’s blocked on another kind of activity, an error is raised as the mandated code is not written yet. "
938           "Please report that bug if you need it.\n\n"
939           "Asynchronous activities started by the actor are not migrated automatically, so you have to take care of "
940           "this yourself (only you knows which ones should be migrated). ")
941       .def_property_readonly("name", &Actor::get_cname, "The name of this actor (read-only property).")
942       .def_property_readonly("pid", &Actor::get_pid, "The PID (unique identifier) of this actor (read-only property).")
943       .def_property_readonly("ppid", &Actor::get_ppid,
944                              "The PID (unique identifier) of the actor that created this one (read-only property).")
945       .def_static("by_pid", &Actor::by_pid, py::arg("pid"), "Retrieve an actor by its PID")
946       .def("set_auto_restart", &Actor::set_auto_restart, py::call_guard<py::gil_scoped_release>(),
947            "Specify whether the actor shall restart when its host reboots.")
948       .def("daemonize", &Actor::daemonize, py::call_guard<py::gil_scoped_release>(),
949            "This actor will be automatically terminated when the last non-daemon actor finishes (more info in the C++ "
950            "documentation).")
951       .def("is_daemon", &Actor::is_daemon,
952            "Returns True if that actor is a daemon and will be terminated automatically when the last non-daemon actor "
953            "terminates.")
954       .def("join", py::overload_cast<double>(&Actor::join, py::const_), py::call_guard<py::gil_scoped_release>(),
955            "Wait for the actor to finish (more info in the C++ documentation).", py::arg("timeout") = -1)
956       .def("kill", &Actor::kill, py::call_guard<py::gil_scoped_release>(), "Kill that actor")
957       .def("self", &Actor::self, "Retrieves the current actor.")
958       .def("is_suspended", &Actor::is_suspended, "Returns True if that actor is currently suspended.")
959       .def("suspend", &Actor::suspend, py::call_guard<py::gil_scoped_release>(),
960            "Suspend that actor, that is blocked until resume()ed by another actor.")
961       .def("resume", &Actor::resume, py::call_guard<py::gil_scoped_release>(),
962            "Resume that actor, that was previously suspend()ed.")
963       .def_static("kill_all", &Actor::kill_all, py::call_guard<py::gil_scoped_release>(), "Kill all actors but the caller.");
964 }