1 /* Copyright (c) 2007-2019. The SimGrid Team. All rights reserved. */
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. */
8 #include "simgrid/s4u/Host.hpp"
9 #include "src/kernel/context/Context.hpp"
10 #include "src/simix/smx_private.hpp"
11 #include "src/surf/surf_interface.hpp"
13 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_context);
16 * @brief creates a new context for a user level process
17 * @param code a main function
18 * @param cleanup_func the function to call when the context stops
19 * @param simix_process
21 smx_context_t SIMIX_context_new(
22 std::function<void()> code,
23 void_pfn_smxprocess_t cleanup_func,
24 smx_actor_t simix_process)
26 return simix_global->context_factory->create_context(
27 std::move(code), cleanup_func, simix_process);
34 ContextFactoryInitializer factory_initializer = nullptr;
36 ContextFactory::~ContextFactory() = default;
38 static thread_local smx_context_t smx_current_context = nullptr;
39 Context* Context::self()
41 return smx_current_context;
43 void Context::set_current(Context* self)
45 smx_current_context = self;
48 void Context::declare_context(std::size_t size)
51 /* Store the address of the stack in heap to compare it apart of heap comparison */
53 MC_ignore_heap(this, size);
57 Context* ContextFactory::attach(void_pfn_smxprocess_t cleanup_func, smx_actor_t process)
59 xbt_die("Cannot attach with this ContextFactory.\n"
60 "Try using --cfg=contexts/factory:thread instead.\n");
63 Context* ContextFactory::create_maestro(std::function<void()> code, smx_actor_t process)
65 xbt_die("Cannot create_maestro with this ContextFactory.\n"
66 "Try using --cfg=contexts/factory:thread instead.\n");
69 Context::Context(std::function<void()> code, void_pfn_smxprocess_t cleanup_func, smx_actor_t actor)
70 : code_(std::move(code)), cleanup_func_(cleanup_func), actor_(actor)
72 /* If no function was provided, this is the context for maestro
73 * and we should set it as the current context */
86 actor_->finished_ = true;
88 if (actor_->auto_restart_ && actor_->host_->is_off()) {
89 XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", actor_->host_->get_cname(),
91 watched_hosts.insert(actor_->host_->get_cname());
94 if (this->cleanup_func_)
95 this->cleanup_func_(this->actor_);
97 this->iwannadie = false; // don't let the yield call ourself -- Context::stop()
98 simgrid::simix::simcall([this] { SIMIX_process_cleanup(this->actor_); });
99 this->iwannadie = true;
102 AttachContext::~AttachContext() = default;
104 void throw_stoprequest()
106 throw Context::StopRequest();
109 bool try_n_catch_stoprequest(std::function<void(void)> try_block)
115 } catch (Context::StopRequest const&) {
116 XBT_DEBUG("Caught a StopRequest");
123 /** @brief Executes all the processes to run (in parallel if possible). */
124 void SIMIX_context_runall()
126 simix_global->context_factory->run_all();