Logo AND Algorithmique Numérique Distribuée

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