Logo AND Algorithmique Numérique Distribuée

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