1 /* Copyright (c) 2009-2018. The SimGrid Team.
2 * All rights reserved. */
4 /* This program is free software; you can redistribute it and/or modify it
5 * under the terms of the license (GNU LGPL) which comes with this package. */
7 /* \file ThreadContext.hpp Context switching with native threads */
9 #ifndef SIMGRID_SIMIX_THREAD_CONTEXT_HPP
10 #define SIMGRID_SIMIX_THREAD_CONTEXT_HPP
12 #include <simgrid/simix.hpp>
19 class ThreadContext : public AttachContext {
21 ThreadContext(std::function<void()> code, void_pfn_smxprocess_t cleanup_func, smx_actor_t process, bool maestro);
22 ~ThreadContext() override;
24 void suspend() override;
25 void attach_start() override;
26 void attach_stop() override;
28 bool isMaestro() const { return is_maestro_; }
29 void release(); // unblock context's start()
30 void wait(); // wait for context's yield()
33 /** A portable thread */
34 xbt_os_thread_t thread_ = nullptr;
35 /** Semaphore used to schedule/yield the process */
36 xbt_os_sem_t begin_ = nullptr;
37 /** Semaphore used to schedule/unschedule */
38 xbt_os_sem_t end_ = nullptr;
41 void start(); // match a call to release()
42 void yield(); // match a call to yield()
43 virtual void start_hook() { /* empty placeholder, called after start() */}
44 virtual void yield_hook() { /* empty placeholder, called before yield() */}
46 static void* wrapper(void *param);
49 class SerialThreadContext : public ThreadContext {
51 SerialThreadContext(std::function<void()> code, void_pfn_smxprocess_t cleanup_func, smx_actor_t process, bool maestro)
52 : ThreadContext(std::move(code), cleanup_func, process, maestro)
56 static void run_all();
59 class ParallelThreadContext : public ThreadContext {
61 ParallelThreadContext(std::function<void()> code, void_pfn_smxprocess_t cleanup_func, smx_actor_t process,
63 : ThreadContext(std::move(code), cleanup_func, process, maestro)
67 static void initialize();
68 static void finalize();
69 static void run_all();
72 static xbt_os_sem_t thread_sem_;
74 void start_hook() override;
75 void yield_hook() override;
78 class ThreadContextFactory : public ContextFactory {
80 ThreadContextFactory();
81 ~ThreadContextFactory() override;
82 ThreadContext* create_context(std::function<void()> code, void_pfn_smxprocess_t cleanup_func,
83 smx_actor_t process) override
85 bool maestro = not code;
86 return create_context(std::move(code), cleanup_func, process, maestro);
88 void run_all() override;
89 ThreadContext* self() override { return static_cast<ThreadContext*>(xbt_os_thread_get_extra_data()); }
92 ThreadContext* attach(void_pfn_smxprocess_t cleanup_func, smx_actor_t process) override
94 return create_context(std::function<void()>(), cleanup_func, process, false);
96 ThreadContext* create_maestro(std::function<void()> code, smx_actor_t process) override
98 return create_context(std::move(code), nullptr, process, true);
104 ThreadContext* create_context(std::function<void()> code, void_pfn_smxprocess_t cleanup_func, smx_actor_t process,