-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathThreadPool.cpp
More file actions
109 lines (91 loc) · 2.52 KB
/
ThreadPool.cpp
File metadata and controls
109 lines (91 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
* SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: LicenseRef-NvidiaProprietary
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#include "ThreadPool.h"
#include <cassert>
namespace ntc
{
ThreadPool::ThreadPool(IAllocator* allocator, uint32_t numThreads)
: m_allocator(allocator)
, m_threads(allocator)
, m_tasks(allocator)
{
assert(numThreads > 0);
m_threads.resize(numThreads);
for (uint32_t i = 0; i < numThreads; ++i)
{
m_threads[i] = std::thread(StaticThreadProc, this);
}
m_ownerThread = std::this_thread::get_id();
}
ThreadPool::~ThreadPool()
{
WaitForTasks();
m_terminate.store(true);
m_forward.notify_all();
for (std::thread& thread : m_threads)
thread.join();
}
void ThreadPool::AddTask(std::shared_ptr<ThreadPoolTask> const& task)
{
assert(std::this_thread::get_id() == m_ownerThread);
{
std::unique_lock<std::mutex> lock(m_mutex);
m_tasks.push(task);
++m_pendingTasks;
}
m_forward.notify_one();
}
bool ThreadPool::WaitForTasks()
{
assert(std::this_thread::get_id() == m_ownerThread);
while(m_pendingTasks.load() != 0)
std::this_thread::yield();
bool success = m_failedTasks.load() == 0;
m_failedTasks.store(0);
return success;
}
void ThreadPool::StaticThreadProc(ThreadPool* self)
{
self->ThreadProc();
}
void ThreadPool::ThreadProc()
{
while(!m_terminate.load())
{
std::shared_ptr<ThreadPoolTask> task;
{
std::unique_lock<std::mutex> lock(m_mutex);
m_forward.wait(lock, [this] { return !m_tasks.empty() || m_terminate.load(); });
if (!m_tasks.empty())
{
task = std::move(m_tasks.front());
m_tasks.pop();
}
}
if (task)
{
try
{
if (!task->Run())
++m_failedTasks;
}
catch(...)
{
++m_failedTasks;
}
--m_pendingTasks;
}
else
std::this_thread::yield();
}
}
}