Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add new entry in Release_Notes.
[simgrid.git] / src / kernel / context / Context.cpp
1 /* Copyright (c) 2007-2023. The SimGrid Team. All rights reserved.          */
2
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. */
5
6 #include "src/mc/mc.h"
7
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
14 #include <vector>
15
16 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_context, kernel, "Context switching mechanism");
17
18 namespace simgrid::kernel::context {
19
20 void Context::set_nthreads(int nb_threads)
21 {
22   if (nb_threads <= 0) {
23     nb_threads = std::thread::hardware_concurrency();
24     XBT_INFO("Auto-setting contexts/nthreads to %d", nb_threads);
25   }
26   Context::parallel_contexts = nb_threads;
27 }
28
29 ContextFactory::~ContextFactory() = default;
30
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;
36
37 /* Install or disable alternate signal stack, for SIGSEGV handler. */
38 int Context::install_sigsegv_stack(bool enable)
39 {
40   static std::vector<unsigned char> sigsegv_stack(SIGSTKSZ);
41   stack_t stack;
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);
46 }
47
48 Context* Context::self()
49 {
50   return current_context_;
51 }
52 void Context::set_current(Context* self)
53 {
54   current_context_ = self;
55 }
56
57 Context* ContextFactory::attach(actor::ActorImpl*)
58 {
59   xbt_die("Cannot attach with this ContextFactory.\n"
60     "Try using --cfg=contexts/factory:thread instead.\n");
61 }
62
63 Context* ContextFactory::create_maestro(std::function<void()>&&, actor::ActorImpl*)
64 {
65   xbt_die("Cannot create_maestro with this ContextFactory.\n"
66     "Try using --cfg=contexts/factory:thread instead.\n");
67 }
68
69 Context::Context(std::function<void()>&& code, actor::ActorImpl* actor, bool maestro)
70     : code_(std::move(code)), actor_(actor), is_maestro_(maestro)
71 {
72   /* If we are creating maestro, we should set it as the current context */
73   if (maestro)
74     set_current(this);
75 }
76
77 Context::~Context()
78 {
79   if (self() == this)
80     set_current(nullptr);
81 }
82
83 void Context::stop()
84 {
85   this->actor_->cleanup_from_self();
86   sthread_disable();
87   throw ForcefulKillException(); // clean RAII variables with the dedicated exception
88 }
89 AttachContext::~AttachContext() = default;
90
91 } // namespace simgrid::kernel::context