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"
16 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_context, kernel, "Context switching mechanism");
18 namespace simgrid::kernel::context {
20 void Context::set_nthreads(int nb_threads)
22 if (nb_threads <= 0) {
23 nb_threads = std::thread::hardware_concurrency();
24 XBT_INFO("Auto-setting contexts/nthreads to %d", nb_threads);
26 Context::parallel_contexts = nb_threads;
29 ContextFactory::~ContextFactory() = default;
31 e_xbt_parmap_mode_t Context::parallel_mode = XBT_PARMAP_DEFAULT;
32 int Context::parallel_contexts = 1;
33 unsigned Context::stack_size;
34 unsigned Context::guard_size;
35 thread_local Context* Context::current_context_ = nullptr;
37 /* Install or disable alternate signal stack, for SIGSEGV handler. */
38 int Context::install_sigsegv_stack(bool enable)
40 static std::vector<unsigned char> sigsegv_stack(SIGSTKSZ);
42 stack.ss_sp = sigsegv_stack.data();
43 stack.ss_size = sigsegv_stack.size();
44 stack.ss_flags = enable ? 0 : SS_DISABLE;
45 return sigaltstack(&stack, nullptr);
48 Context* Context::self()
50 return current_context_;
52 void Context::set_current(Context* self)
54 current_context_ = self;
57 void Context::declare_context(std::size_t size)
59 /* Store the address of the stack in heap to compare it apart of heap comparison */
60 MC_ignore_heap(this, size);
63 Context* ContextFactory::attach(actor::ActorImpl*)
65 xbt_die("Cannot attach with this ContextFactory.\n"
66 "Try using --cfg=contexts/factory:thread instead.\n");
69 Context* ContextFactory::create_maestro(std::function<void()>&&, actor::ActorImpl*)
71 xbt_die("Cannot create_maestro with this ContextFactory.\n"
72 "Try using --cfg=contexts/factory:thread instead.\n");
75 Context::Context(std::function<void()>&& code, actor::ActorImpl* actor, bool maestro)
76 : code_(std::move(code)), actor_(actor), is_maestro_(maestro)
78 /* If we are creating maestro, we should set it as the current context */
91 this->actor_->cleanup_from_self();
93 throw ForcefulKillException(); // clean RAII variables with the dedicated exception
95 AttachContext::~AttachContext() = default;
97 } // namespace simgrid::kernel::context