1 /* Copyright (c) 2007-2023. 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/Exception.hpp"
9 #include "simgrid/s4u/Host.hpp"
10 #include "src/kernel/activity/CommImpl.hpp"
11 #include "src/kernel/context/Context.hpp"
12 #include "src/sthread/sthread.h"
13 #include "src/surf/surf_interface.hpp"
17 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_context, kernel, "Context switching mechanism");
19 namespace simgrid::kernel::context {
21 void Context::set_nthreads(int nb_threads)
23 if (nb_threads <= 0) {
24 nb_threads = std::thread::hardware_concurrency();
25 XBT_INFO("Auto-setting contexts/nthreads to %d", nb_threads);
27 Context::parallel_contexts = nb_threads;
30 ContextFactory::~ContextFactory() = default;
32 e_xbt_parmap_mode_t Context::parallel_mode = XBT_PARMAP_DEFAULT;
33 int Context::parallel_contexts = 1;
34 unsigned Context::stack_size;
35 unsigned Context::guard_size;
36 thread_local Context* Context::current_context_ = nullptr;
38 /* Install or disable alternate signal stack, for SIGSEGV handler. */
39 int Context::install_sigsegv_stack(bool enable)
41 static std::vector<unsigned char> sigsegv_stack(SIGSTKSZ);
43 stack.ss_sp = sigsegv_stack.data();
44 stack.ss_size = sigsegv_stack.size();
45 stack.ss_flags = enable ? 0 : SS_DISABLE;
46 return sigaltstack(&stack, nullptr);
49 Context* Context::self()
51 return current_context_;
53 void Context::set_current(Context* self)
55 current_context_ = self;
58 void Context::declare_context(std::size_t size)
60 /* Store the address of the stack in heap to compare it apart of heap comparison */
61 MC_ignore_heap(this, size);
64 Context* ContextFactory::attach(actor::ActorImpl*)
66 xbt_die("Cannot attach with this ContextFactory.\n"
67 "Try using --cfg=contexts/factory:thread instead.\n");
70 Context* ContextFactory::create_maestro(std::function<void()>&&, actor::ActorImpl*)
72 xbt_die("Cannot create_maestro with this ContextFactory.\n"
73 "Try using --cfg=contexts/factory:thread instead.\n");
76 Context::Context(std::function<void()>&& code, actor::ActorImpl* actor, bool maestro)
77 : code_(std::move(code)), actor_(actor), is_maestro_(maestro)
79 /* If we are creating maestro, we should set it as the current context */
92 this->actor_->cleanup_from_self();
94 throw ForcefulKillException(); // clean RAII variables with the dedicated exception
96 AttachContext::~AttachContext() = default;
98 } // namespace simgrid::kernel::context