1 /* Copyright (c) 2009-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. */
6 #ifndef SIMGRID_SIMIX_RAW_CONTEXT_HPP
7 #define SIMGRID_SIMIX_RAW_CONTEXT_HPP
14 #include <xbt/parmap.hpp>
15 #include <xbt/xbt_os_thread.h>
21 /** @brief Fast context switching inspired from SystemV ucontexts.
23 * The main difference to the System V context is that Raw Contexts are much faster because they don't
24 * preserve the signal mask when switching. This saves a system call (at least on Linux) on each context switch.
26 class RawContext : public Context {
28 RawContext(std::function<void()> code, void_pfn_smxprocess_t cleanup_func, smx_actor_t process);
29 ~RawContext() override;
31 virtual void resume() = 0;
33 static void swap(RawContext* from, RawContext* to);
34 static RawContext* getMaestro() { return maestro_context_; }
35 static void setMaestro(RawContext* maestro) { maestro_context_ = maestro; }
38 static RawContext* maestro_context_;
39 void* stack_ = nullptr;
40 /** pointer to top the stack stack */
41 void* stack_top_ = nullptr;
43 #if HAVE_SANITIZE_ADDRESS_FIBER_SUPPORT
44 const void* asan_stack_ = nullptr;
45 size_t asan_stack_size_ = 0;
46 RawContext* asan_ctx_ = nullptr;
47 bool asan_stop_ = false;
50 static void wrapper(void* arg);
53 class SerialRawContext : public RawContext {
55 SerialRawContext(std::function<void()> code, void_pfn_smxprocess_t cleanup_func, smx_actor_t process)
56 : RawContext(std::move(code), cleanup_func, process)
59 void suspend() override;
60 void resume() override;
62 static void run_all();
65 static unsigned long process_index_;
68 #if HAVE_THREAD_CONTEXTS
69 class ParallelRawContext : public RawContext {
71 ParallelRawContext(std::function<void()> code, void_pfn_smxprocess_t cleanup_func, smx_actor_t process)
72 : RawContext(std::move(code), cleanup_func, process)
75 void suspend() override;
76 void resume() override;
78 static void initialize();
79 static void finalize();
80 static void run_all();
83 static simgrid::xbt::Parmap<smx_actor_t>* parmap_;
84 static std::vector<ParallelRawContext*> workers_context_;
85 static std::atomic<uintptr_t> threads_working_;
86 static uintptr_t thread_local worker_id_;
90 class RawContextFactory : public ContextFactory {
93 ~RawContextFactory() override;
94 Context* create_context(std::function<void()> code, void_pfn_smxprocess_t cleanup, smx_actor_t process) override;
95 void run_all() override;