1 /* Copyright (c) 2007-2018. 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 "src/kernel/context/Context.hpp"
9 #include "src/simix/smx_private.hpp"
12 * @brief creates a new context for a user level process
13 * @param code a main function
14 * @param cleanup_func the function to call when the context stops
15 * @param simix_process
17 smx_context_t SIMIX_context_new(
18 std::function<void()> code,
19 void_pfn_smxprocess_t cleanup_func,
20 smx_actor_t simix_process)
22 xbt_assert(simix_global, "simix is not initialized, please call MSG_init first");
23 return simix_global->context_factory->create_context(
24 std::move(code), cleanup_func, simix_process);
31 ContextFactoryInitializer factory_initializer = nullptr;
33 ContextFactory::~ContextFactory() = default;
35 Context* ContextFactory::self()
37 return SIMIX_context_get_current();
40 void ContextFactory::declare_context(void* context, std::size_t size)
43 /* Store the address of the stack in heap to compare it apart of heap comparison */
45 MC_ignore_heap(context, size);
49 Context* ContextFactory::attach(void_pfn_smxprocess_t cleanup_func, smx_actor_t process)
51 xbt_die("Cannot attach with this ContextFactory.\n"
52 "Try using --cfg=contexts/factory:thread instead.\n");
55 Context* ContextFactory::create_maestro(std::function<void()> code, smx_actor_t process)
57 xbt_die("Cannot create_maestro with this ContextFactory.\n"
58 "Try using --cfg=contexts/factory:thread instead.\n");
61 Context::Context(std::function<void()> code,
62 void_pfn_smxprocess_t cleanup_func, smx_actor_t process)
63 : code_(std::move(code)), process_(process), iwannadie(false)
65 /* If the user provided a function for the process then use it.
66 Otherwise, it is the context for maestro and we should set it as the
69 this->cleanup_func_ = cleanup_func;
71 SIMIX_context_set_current(this);
74 Context::~Context() = default;
78 if (this->cleanup_func_)
79 this->cleanup_func_(this->process_);
80 this->process_->suspended_ = 0;
82 this->iwannadie = false;
83 simgrid::simix::simcall([this] { SIMIX_process_cleanup(this->process_); });
84 this->iwannadie = true;
87 AttachContext::~AttachContext() = default;
91 /** @brief Executes all the processes to run (in parallel if possible). */
92 void SIMIX_context_runall()
94 simix_global->context_factory->run_all();
97 /** @brief returns the current running context */
98 smx_context_t SIMIX_context_self()
100 if (simix_global && simix_global->context_factory)
101 return simix_global->context_factory->self();