SHiP Geometry Service
Framework-agnostic C++20 library wrapping the SHiP GeoModel geometry behind a stable interface.
Loading...
Searching...
No Matches
GeometryThread.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 CERN for the benefit of the SHiP Collaboration
2//
3// SPDX-License-Identifier: LGPL-3.0-or-later
4#pragma once
5
6#include <thread>
7#include <type_traits>
8
9#include <concepts>
10#include <condition_variable>
11#include <deque>
12#include <functional>
13#include <future>
14#include <mutex>
15#include <stop_token>
16#include <utility>
17
18namespace ship {
19
28 public:
29 // jthread requests stop and joins; queued tasks are drained first.
30 ~GeometryThread() = default;
31
36
40 // Constrained on lvalue invocation: f is called as an lvalue here and
41 // by the packaged_task below.
42 template <typename F>
43 requires std::invocable<F&>
44 std::invoke_result_t<F&> run(F&& f) {
45 if (std::this_thread::get_id() == m_thread.get_id())
46 return f();
47 using R = std::invoke_result_t<F&>;
48 std::packaged_task<R()> task{std::forward<F>(f)};
49 auto result = task.get_future();
50 // The reference capture is safe: result.get() below keeps this frame
51 // alive until the task has run.
52 post([&task] { task(); });
53 return result.get();
54 }
55
56 private:
57 // Constructible only through geometry_thread(): a second instance would
58 // break the single geometry-creating-thread invariant documented there.
61
62 void post(std::function<void()> task);
63 void loop(std::stop_token stopToken);
64
65 std::mutex m_mutex;
66 std::condition_variable_any m_cv;
67 std::deque<std::function<void()>> m_tasks;
68 std::jthread m_thread;
69};
70
80GeometryThread& geometry_thread();
81
82} // namespace ship
Runs posted tasks on one dedicated thread until destroyed.
Definition GeometryThread.h:27
GeometryThread(const GeometryThread &)=delete
~GeometryThread()=default
GeometryThread & operator=(GeometryThread &&)=delete
GeometryThread(GeometryThread &&)=delete
std::invoke_result_t< F & > run(F &&f)
Run f on the geometry thread and return its result.
Definition GeometryThread.h:44
GeometryThread & operator=(const GeometryThread &)=delete
friend GeometryThread & geometry_thread()
The process-wide Geant4 geometry thread, shared by every geometry user (GENIE geometry analyzers,...
Definition GeometryThread.cpp:35
Definition G4RayScanner.h:15
GeometryThread & geometry_thread()
The process-wide Geant4 geometry thread, shared by every geometry user (GENIE geometry analyzers,...
Definition GeometryThread.cpp:35