]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdbsupport/task-group.cc
Update copyright year range in header of all files managed by GDB
[thirdparty/binutils-gdb.git] / gdbsupport / task-group.cc
1 /* Task group
2
3 Copyright (C) 2023-2024 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 #include "common-defs.h"
21 #include "task-group.h"
22 #include "thread-pool.h"
23
24 namespace gdb
25 {
26
27 class task_group::impl : public std::enable_shared_from_this<task_group::impl>
28 {
29 public:
30
31 explicit impl (std::function<void ()> &&done)
32 : m_done (std::move (done))
33 { }
34 DISABLE_COPY_AND_ASSIGN (impl);
35
36 ~impl ()
37 {
38 if (m_started)
39 m_done ();
40 }
41
42 /* Add a task to the task group. */
43 void add_task (std::function<void ()> &&task)
44 {
45 m_tasks.push_back (std::move (task));
46 };
47
48 /* Start this task group. */
49 void start ();
50
51 /* True if started. */
52 bool m_started = false;
53 /* The tasks. */
54 std::vector<std::function<void ()>> m_tasks;
55 /* The 'done' function. */
56 std::function<void ()> m_done;
57 };
58
59 void
60 task_group::impl::start ()
61 {
62 std::shared_ptr<impl> shared_this = shared_from_this ();
63 m_started = true;
64 for (size_t i = 0; i < m_tasks.size (); ++i)
65 {
66 gdb::thread_pool::g_thread_pool->post_task ([=] ()
67 {
68 /* Be sure to capture a shared reference here. */
69 shared_this->m_tasks[i] ();
70 });
71 }
72 }
73
74 task_group::task_group (std::function<void ()> &&done)
75 : m_task (new impl (std::move (done)))
76 {
77 }
78
79 void
80 task_group::add_task (std::function<void ()> &&task)
81 {
82 gdb_assert (m_task != nullptr);
83 m_task->add_task (std::move (task));
84 }
85
86 void
87 task_group::start ()
88 {
89 gdb_assert (m_task != nullptr);
90 m_task->start ();
91 m_task.reset ();
92 }
93
94 } /* namespace gdb */