Logo AND Algorithmique Numérique Distribuée

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