+ SwappedContext::set_maestro(nullptr);
+ SwappedContext::initialize(parallel_);
+}
+SwappedContextFactory::~SwappedContextFactory()
+{
+ SwappedContext::finalize();
+}
+/** Maestro wants to run all ready actors */
+void SwappedContextFactory::run_all()
+{
+ /* This function is called by maestro at the beginning of a scheduling round to get all working threads executing some
+ * stuff It is much easier to understand what happens if you see the working threads as bodies that swap their soul
+ * for the ones of the simulated processes that must run.
+ */
+ if (parallel_) {
+ SwappedContext::threads_working_ = 0;
+
+ // We lazily create the parmap so that all options are actually processed when doing so.
+ if (SwappedContext::parmap_ == nullptr)
+ SwappedContext::parmap_ =
+ new simgrid::xbt::Parmap<smx_actor_t>(SIMIX_context_get_nthreads(), SIMIX_context_get_parallel_mode());
+
+ // Usually, Parmap::apply() executes the provided function on all elements of the array.
+ // Here, the executed function does not return the control to the parmap before all the array is processed:
+ // - suspend() should switch back to the worker_context (either maestro or one of its minions) to return
+ // the control to the parmap. Instead, it uses parmap_->next() to steal another work, and does it directly.
+ // It only yields back to worker_context when the work array is exhausted.
+ // - So, resume() is only launched from the parmap for the first job of each minion.
+ SwappedContext::parmap_->apply(
+ [](smx_actor_t process) {
+ SwappedContext* context = static_cast<SwappedContext*>(process->context_);
+ context->resume();
+ },
+ simix_global->process_to_run);
+ } else { // sequential execution
+ if (simix_global->process_to_run.empty())
+ return;
+ smx_actor_t first_actor = simix_global->process_to_run.front();
+ process_index_ = 1;
+ /* execute the first actor; it will chain to the others when using suspend() */
+ static_cast<SwappedContext*>(first_actor->context_)->resume();
+ }
+}
+
+void SwappedContext::initialize(bool parallel)
+{
+ parmap_ = nullptr; // will be created lazily with the right parameters if needed (ie, in parallel)
+ if (parallel) {
+ workers_context_.clear();
+ workers_context_.resize(SIMIX_context_get_nthreads(), nullptr);
+ }