/work/vvenc/source/Lib/Utilities/NoMallocThreadPool.cpp
Line | Count | Source |
1 | | /* ----------------------------------------------------------------------------- |
2 | | The copyright in this software is being made available under the Clear BSD |
3 | | License, included below. No patent rights, trademark rights and/or |
4 | | other Intellectual Property Rights other than the copyrights concerning |
5 | | the Software are granted under this license. |
6 | | |
7 | | The Clear BSD License |
8 | | |
9 | | Copyright (c) 2019-2026, Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V. & The VVenC Authors. |
10 | | All rights reserved. |
11 | | |
12 | | Redistribution and use in source and binary forms, with or without modification, |
13 | | are permitted (subject to the limitations in the disclaimer below) provided that |
14 | | the following conditions are met: |
15 | | |
16 | | * Redistributions of source code must retain the above copyright notice, |
17 | | this list of conditions and the following disclaimer. |
18 | | |
19 | | * Redistributions in binary form must reproduce the above copyright |
20 | | notice, this list of conditions and the following disclaimer in the |
21 | | documentation and/or other materials provided with the distribution. |
22 | | |
23 | | * Neither the name of the copyright holder nor the names of its |
24 | | contributors may be used to endorse or promote products derived from this |
25 | | software without specific prior written permission. |
26 | | |
27 | | NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY |
28 | | THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND |
29 | | CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
30 | | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A |
31 | | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR |
32 | | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, |
33 | | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
34 | | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR |
35 | | BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER |
36 | | IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
37 | | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
38 | | POSSIBILITY OF SUCH DAMAGE. |
39 | | |
40 | | |
41 | | ------------------------------------------------------------------------------------------- */ |
42 | | |
43 | | |
44 | | /** \file NoMallocThreadPool.cpp |
45 | | \brief thread pool |
46 | | */ |
47 | | |
48 | | #include "NoMallocThreadPool.h" |
49 | | |
50 | | #include <limits> |
51 | | |
52 | | #ifdef HAVE_PTHREADS |
53 | | # include <pthread.h> |
54 | 5.72k | # define THREAD_MIN_STACK_SIZE 1024 * 1024 |
55 | | #endif |
56 | | |
57 | | |
58 | | //! \ingroup Utilities |
59 | | //! \{ |
60 | | |
61 | | namespace vvenc { |
62 | | |
63 | | #if ENABLE_TIME_PROFILING_MT_MODE |
64 | | thread_local std::unique_ptr<TProfiler> ptls; |
65 | | #endif |
66 | | |
67 | | NoMallocThreadPool::NoMallocThreadPool( int numThreads, const char * threadPoolName, const VVEncCfg* encCfg ) |
68 | 1.43k | : NoMallocThreadPool( numThreads, threadPoolName, encCfg, BUSY_WAIT_TIME, std::chrono::milliseconds( 50 ) ) |
69 | 1.43k | { |
70 | 1.43k | } |
71 | | |
72 | | NoMallocThreadPool::NoMallocThreadPool( int numThreads, const char * threadPoolName, const VVEncCfg* encCfg, |
73 | | std::chrono::microseconds idleBusyWait, std::chrono::milliseconds safetyWakeInterval ) |
74 | 1.43k | : m_poolName( threadPoolName ) |
75 | 1.43k | , m_idleBusyWait( idleBusyWait ) |
76 | 1.43k | , m_safetyWakeInterval( safetyWakeInterval ) |
77 | 1.43k | { |
78 | 1.43k | if( numThreads < 0 ) |
79 | 0 | { |
80 | 0 | numThreads = std::thread::hardware_concurrency(); |
81 | 0 | } |
82 | | |
83 | 7.16k | for( int i = 0; i < numThreads; ++i ) |
84 | 5.72k | { |
85 | 5.72k | m_threads.emplace_back( &NoMallocThreadPool::threadProc, this, i, *encCfg ); |
86 | 5.72k | } |
87 | 1.43k | } |
88 | | |
89 | | NoMallocThreadPool::~NoMallocThreadPool() |
90 | 1.43k | { |
91 | 1.43k | m_exitThreads = true; |
92 | 1.43k | wakeIdleThread(); |
93 | | |
94 | 1.43k | waitForThreads(); |
95 | 1.43k | } |
96 | | |
97 | | bool NoMallocThreadPool::processTasksOnMainThread() |
98 | 0 | { |
99 | 0 | CHECK( m_threads.size() != 0, "should not be used with multiple threads" ); |
100 | |
|
101 | 0 | bool progress = false; |
102 | 0 | TaskIterator firstFailedIt = m_tasks.end(); |
103 | 0 | for( auto taskIt = findNextTask( 0, m_tasks.begin() ); taskIt.isValid(); taskIt = findNextTask( 0, taskIt ) ) |
104 | 0 | { |
105 | 0 | const bool success = processTask( 0, *taskIt ); |
106 | 0 | progress |= success; |
107 | |
|
108 | 0 | if( taskIt == firstFailedIt ) |
109 | 0 | { |
110 | 0 | if( success ) |
111 | 0 | { |
112 | | // first failed was successful -> reset |
113 | 0 | firstFailedIt = m_tasks.end(); |
114 | 0 | } |
115 | 0 | else if( progress ) |
116 | 0 | { |
117 | | // reset progress, try another round |
118 | 0 | progress = false; |
119 | 0 | } |
120 | 0 | else |
121 | 0 | { |
122 | | // no progress -> exit |
123 | 0 | break; |
124 | 0 | } |
125 | 0 | } |
126 | 0 | else if( !success && !firstFailedIt.isValid() ) |
127 | 0 | { |
128 | 0 | firstFailedIt = taskIt; |
129 | 0 | } |
130 | 0 | } |
131 | | |
132 | | // return true if all done (-> false if some tasks blocked due to barriers) |
133 | 0 | return std::all_of( m_tasks.begin(), m_tasks.end(), []( Slot& t ) { return t.state == FREE; } ); |
134 | 0 | } |
135 | | |
136 | | void NoMallocThreadPool::shutdown( bool block ) |
137 | 1.43k | { |
138 | 1.43k | m_exitThreads = true; |
139 | 1.43k | wakeIdleThread(); |
140 | 1.43k | if( block ) |
141 | 1.43k | { |
142 | 1.43k | waitForThreads(); |
143 | 1.43k | } |
144 | 1.43k | } |
145 | | |
146 | | void NoMallocThreadPool::waitForThreads() |
147 | 2.86k | { |
148 | 2.86k | for( auto& t: m_threads ) |
149 | 11.4k | { |
150 | 11.4k | if( t.joinable() ) |
151 | 5.72k | t.join(); |
152 | 11.4k | } |
153 | 2.86k | } |
154 | | |
155 | | void NoMallocThreadPool::threadProc( int threadId, const VVEncCfg& encCfg ) |
156 | 5.72k | { |
157 | 5.72k | #if __linux |
158 | 5.72k | if( !m_poolName.empty() ) |
159 | 5.72k | { |
160 | 5.72k | std::string threadName( m_poolName + std::to_string( threadId ) ); |
161 | 5.72k | pthread_setname_np( pthread_self(), threadName.c_str() ); |
162 | 5.72k | } |
163 | 5.72k | #endif |
164 | | #if ENABLE_TIME_PROFILING_MT_MODE |
165 | | ptls.reset( timeProfilerCreate( encCfg ) ); |
166 | | { |
167 | | std::unique_lock< std::mutex > lock( m_nextFillSlotMutex ); |
168 | | TProfiler *tp = ptls.get(); |
169 | | profilers.push_back( tp ); |
170 | | } |
171 | | #endif |
172 | | |
173 | 5.72k | auto nextTaskIt = m_tasks.begin(); |
174 | 38.4k | while( !m_exitThreads ) |
175 | 38.4k | { |
176 | 38.4k | bool rescheduled = false; |
177 | 38.4k | auto taskIt = findNextTask( threadId, nextTaskIt, &rescheduled ); |
178 | 38.4k | if( rescheduled ) |
179 | 18.7k | { |
180 | | // a slot this thread held for its ready check was invisible to the idle thread's last scan |
181 | 18.7k | wakeIdleThread(); |
182 | 18.7k | } |
183 | 38.4k | if( !taskIt.isValid() ) |
184 | 18.0k | { |
185 | 18.0k | taskIt = waitForTask( threadId, nextTaskIt ); |
186 | 18.0k | } |
187 | 38.4k | if( m_exitThreads || !taskIt.isValid() ) |
188 | 5.72k | { |
189 | 5.72k | return; |
190 | 5.72k | } |
191 | | |
192 | 32.7k | processTask( threadId, *taskIt ); |
193 | | // a task that ran, finished or not, may have made other tasks ready |
194 | 32.7k | wakeIdleThread(); |
195 | | |
196 | 32.7k | nextTaskIt = taskIt; |
197 | 32.7k | nextTaskIt.incWrap(); |
198 | 32.7k | } |
199 | 5.72k | } |
200 | | |
201 | | // Called when a scan found nothing to run. One idle thread at a time looks for work: the owner of m_idleMutex; the |
202 | | // others wait for the mutex. The owner busy-waits m_idleBusyWait (while the pool is busy, tasks become ready within |
203 | | // microseconds), then sleeps until a task is added, runs or makes progress (wakeIdleThread), so the CPU stays free |
204 | | // while the encoder waits, e.g. for input. |
205 | | NoMallocThreadPool::TaskIterator NoMallocThreadPool::waitForTask( int threadId, TaskIterator startSearch ) |
206 | 18.0k | { |
207 | 18.0k | ITT_TASKSTART( itt_domain_thrd, itt_handle_TPblocked ); |
208 | 18.0k | std::unique_lock<std::mutex> idleLock( m_idleMutex ); |
209 | 18.0k | ITT_TASKEND( itt_domain_thrd, itt_handle_TPblocked ); |
210 | | |
211 | 18.0k | ITT_TASKSTART( itt_domain_thrd, itt_handle_TPspinWait ); |
212 | 18.0k | TaskIterator taskIt; |
213 | 18.0k | bool afterTimeout = false; |
214 | 18.0k | auto sleepAt = std::chrono::steady_clock::now() + m_idleBusyWait; |
215 | 7.97M | while( !m_exitThreads ) |
216 | 7.97M | { |
217 | 7.97M | taskIt = findNextTask( threadId, startSearch ); |
218 | 7.97M | if( taskIt.isValid() ) |
219 | 12.3k | { |
220 | 12.3k | if( afterTimeout ) |
221 | 0 | { |
222 | 0 | m_wakeUpsMissed.fetch_add( 1, std::memory_order_relaxed ); |
223 | 0 | } |
224 | 12.3k | break; |
225 | 12.3k | } |
226 | 7.95M | afterTimeout = false; |
227 | 7.95M | if( std::chrono::steady_clock::now() < sleepAt ) |
228 | 7.94M | { |
229 | 7.94M | std::this_thread::yield(); |
230 | 7.94M | continue; |
231 | 7.94M | } |
232 | | |
233 | | // Sleep. The flag is set before the last scan and producers check it after publishing their change, both behind |
234 | | // a full fence: either the scan sees the change or the producer sees the flag, so no wake-up is lost. |
235 | 9.75k | m_idleThreadSleeps.store( true ); |
236 | 9.75k | std::atomic_thread_fence( std::memory_order_seq_cst ); |
237 | 9.75k | taskIt = findNextTask( threadId, startSearch ); |
238 | 9.75k | if( taskIt.isValid() || m_exitThreads ) |
239 | 7 | { |
240 | 7 | m_idleThreadSleeps.store( false ); // a notify that may still come finds no sleeper, which is harmless |
241 | 7 | break; |
242 | 7 | } |
243 | 9.74k | { |
244 | 9.74k | std::unique_lock<std::mutex> sleepLock( m_sleepMutex ); |
245 | | // safety net: look again at least every m_safetyWakeInterval (50 ms) |
246 | 19.4k | const bool woken = m_sleepCond.wait_for( sleepLock, m_safetyWakeInterval, [this] { return !m_idleThreadSleeps.load() || m_exitThreads; } ); |
247 | | // false from the exchange: a producer took the flag just now, so it did not miss this sleep |
248 | 9.74k | afterTimeout = !woken && m_idleThreadSleeps.exchange( false ); |
249 | 9.74k | } |
250 | 9.74k | sleepAt = std::chrono::steady_clock::now() + m_idleBusyWait; |
251 | 9.74k | } |
252 | 18.0k | ITT_TASKEND( itt_domain_thrd, itt_handle_TPspinWait ); |
253 | 18.0k | return taskIt; // unlocking m_idleMutex lets the next waiting thread look for work |
254 | 18.0k | } |
255 | | |
256 | | // After a change that can make a task ready: wake the idle thread if it sleeps (one fence and one load otherwise). |
257 | | void NoMallocThreadPool::wakeIdleThread() |
258 | 65.8k | { |
259 | 65.8k | std::atomic_thread_fence( std::memory_order_seq_cst ); |
260 | 65.8k | if( m_idleThreadSleeps.load( std::memory_order_relaxed ) && m_idleThreadSleeps.exchange( false ) ) |
261 | 9.75k | { |
262 | 9.75k | { |
263 | | // Empty on purpose. The sleeper checks the flag while it holds this mutex and gives the mutex up only inside |
264 | | // wait_for. So once this thread had the mutex, the sleeper either finds the flag cleared and does not wait, or |
265 | | // it is inside wait_for already and gets the notify. No wake-up is lost, and it need not wait for this mutex |
266 | | // when it wakes up, as it would if the notify came under the lock. |
267 | 9.75k | std::lock_guard<std::mutex> sleepLock( m_sleepMutex ); |
268 | 9.75k | } |
269 | 9.75k | m_sleepCond.notify_one(); |
270 | 9.75k | } |
271 | 65.8k | } |
272 | | |
273 | | // Returns the most urgent ready task (lowest priority value), claimed (RUNNING); among equally urgent ones the first one |
274 | | // from startSearch, so the threads spread over the queue. Only a task more urgent than the best one found so far gets its |
275 | | // barriers and ready check tested; a ready task of priority 0 ends the search at once. A claimed task that a more urgent |
276 | | // one replaces goes back to WAITING (reported as rescheduled, like a failed ready check). |
277 | | NoMallocThreadPool::TaskIterator NoMallocThreadPool::findNextTask( int threadId, TaskIterator startSearch, bool* rescheduled ) |
278 | 8.01M | { |
279 | 8.01M | if( !startSearch.isValid() ) |
280 | 0 | { |
281 | 0 | startSearch = m_tasks.begin(); |
282 | 0 | } |
283 | 8.01M | TaskIterator best; |
284 | 8.01M | int64_t bestPriority = std::numeric_limits<int64_t>::max(); |
285 | 8.01M | bool first = true; |
286 | 1.03G | for( auto it = startSearch; it != startSearch || first; it.incWrap() ) |
287 | 1.02G | { |
288 | | #if ENABLE_VALGRIND_CODE |
289 | | MutexLock lock( m_extraMutex ); |
290 | | #endif |
291 | | |
292 | 1.02G | first = false; |
293 | | |
294 | 1.02G | Slot& t = *it; |
295 | 1.02G | if( t.state.load( std::memory_order_relaxed ) != WAITING || t.priority.load( std::memory_order_relaxed ) >= bestPriority ) |
296 | 1.00G | { |
297 | 1.00G | continue; |
298 | 1.00G | } |
299 | 20.1M | auto expected = WAITING; |
300 | 20.1M | if( !t.state.compare_exchange_strong( expected, RUNNING ) ) |
301 | 716 | { |
302 | 716 | continue; |
303 | 716 | } |
304 | | // read again now that the slot is ours: it may have been refilled since the first read |
305 | 20.1M | const int64_t priority = t.priority.load( std::memory_order_relaxed ); |
306 | 20.1M | bool ready = priority < bestPriority; |
307 | 20.1M | if( ready && !t.barriers.empty() ) |
308 | 6.30M | { |
309 | 6.30M | ready = std::none_of( t.barriers.cbegin(), t.barriers.cend(), []( const Barrier* b ) { return b && b->isBlocked(); } ); |
310 | 6.30M | if( ready ) |
311 | 1.43k | { |
312 | 1.43k | t.barriers.clear(); // clear barriers, so we don't need to check them on the next try (we assume they won't get locked again) |
313 | 1.43k | } |
314 | 6.30M | } |
315 | 20.1M | ready = ready && ( !t.readyCheck || t.readyCheck( threadId, t.param ) ); |
316 | 20.1M | if( !ready ) |
317 | 20.1M | { |
318 | | // give the slot back: not more urgent than the best (refilled since the first read), blocked by a barrier, or not |
319 | | // ready yet; it was invisible to other scans meanwhile, so the caller wakes the idle thread |
320 | 20.1M | t.state.store( WAITING ); |
321 | 20.1M | if( rescheduled ) *rescheduled = true; |
322 | 20.1M | continue; |
323 | 20.1M | } |
324 | | |
325 | 10.3k | if( best.isValid() ) |
326 | 0 | { |
327 | 0 | ( *best ).state.store( WAITING ); |
328 | 0 | if( rescheduled ) *rescheduled = true; |
329 | 0 | } |
330 | 10.3k | best = it; |
331 | 10.3k | bestPriority = priority; |
332 | 10.3k | if( priority == 0 ) |
333 | 1.43k | { |
334 | 1.43k | break; // nothing is more urgent |
335 | 1.43k | } |
336 | 10.3k | } |
337 | 8.01M | return best; |
338 | 8.01M | } |
339 | | |
340 | | bool NoMallocThreadPool::processTask( int threadId, NoMallocThreadPool::Slot& task ) |
341 | 32.7k | { |
342 | 32.7k | const bool success = task.func( threadId, task.param ); |
343 | | #if ENABLE_VALGRIND_CODE |
344 | | MutexLock lock( m_extraMutex ); |
345 | | #endif |
346 | 32.7k | if( !success ) |
347 | 25.2k | { |
348 | 25.2k | task.state = WAITING; |
349 | 25.2k | return false; |
350 | 25.2k | } |
351 | | |
352 | 7.51k | if( task.done != nullptr ) |
353 | 0 | { |
354 | 0 | task.done->unlock(); |
355 | 0 | } |
356 | 7.51k | if( task.counter != nullptr ) |
357 | 4.65k | { |
358 | 4.65k | --(*task.counter); |
359 | 4.65k | } |
360 | | |
361 | 7.51k | task.state = FREE; |
362 | | |
363 | 7.51k | return true; |
364 | 32.7k | } |
365 | | |
366 | | #ifdef HAVE_PTHREADS |
367 | | |
368 | | template<class TFunc, class... TArgs> |
369 | | NoMallocThreadPool::PThread::PThread( TFunc&& func, TArgs&&... args ) |
370 | 5.72k | { |
371 | 5.72k | using WrappedCall = std::function<void()>; |
372 | 5.72k | std::unique_ptr<WrappedCall> call = std::make_unique<WrappedCall>( std::bind( func, args... ) ); |
373 | | |
374 | 5.72k | using PThreadsStartFn = void* (*) ( void* ); |
375 | 5.72k | PThreadsStartFn threadFn = []( void* p ) -> void* |
376 | 5.72k | { |
377 | 5.72k | std::unique_ptr<WrappedCall> call( static_cast<WrappedCall*>( p ) ); |
378 | | |
379 | 5.72k | ( *call )(); |
380 | | |
381 | 5.72k | return nullptr; |
382 | 5.72k | }; |
383 | | |
384 | 5.72k | pthread_attr_t attr; |
385 | 5.72k | int ret = pthread_attr_init( &attr ); |
386 | 5.72k | CHECK( ret != 0, "pthread_attr_init() failed" ); |
387 | | |
388 | 5.72k | try |
389 | 5.72k | { |
390 | 5.72k | size_t currStackSize = 0; |
391 | 5.72k | ret = pthread_attr_getstacksize( &attr, &currStackSize ); |
392 | 5.72k | CHECK( ret != 0, "pthread_attr_getstacksize() failed" ); |
393 | | |
394 | 5.72k | if( currStackSize < THREAD_MIN_STACK_SIZE ) |
395 | 0 | { |
396 | 0 | ret = pthread_attr_setstacksize( &attr, THREAD_MIN_STACK_SIZE ); |
397 | 0 | CHECK( ret != 0, "pthread_attr_setstacksize() failed" ); |
398 | |
|
399 | 0 | # if defined( _DEBUG ) && !defined( __MINGW32__ ) && !defined( __MINGW64__ ) |
400 | 0 | ret = pthread_attr_setguardsize( &attr, 1024 * 1024 ); // set stack guard size to 1MB to more reliably deteck stack overflows |
401 | 0 | CHECK( ret != 0, "pthread_attr_setguardsize() failed" ); |
402 | 0 | # endif |
403 | 0 | } |
404 | 5.72k | m_joinable = 0 == pthread_create( &m_id, &attr, threadFn, call.get() ); |
405 | 5.72k | CHECK( !m_joinable, "pthread_create() faild" ); |
406 | | |
407 | 5.72k | call.release(); // will now be freed by the thread |
408 | | |
409 | 5.72k | pthread_attr_destroy( &attr ); |
410 | 5.72k | } |
411 | 5.72k | catch( ... ) |
412 | 5.72k | { |
413 | 0 | pthread_attr_destroy( &attr ); |
414 | 0 | throw; |
415 | 0 | } |
416 | 5.72k | } |
417 | | |
418 | | NoMallocThreadPool::PThread& NoMallocThreadPool::PThread::operator=( PThread&& other ) |
419 | 4.29k | { |
420 | 4.29k | m_id = other.m_id; |
421 | 4.29k | m_joinable = other.m_joinable; |
422 | 4.29k | other.m_id = 0; |
423 | 4.29k | other.m_joinable = false; |
424 | 4.29k | return *this; |
425 | 4.29k | } |
426 | | |
427 | | void NoMallocThreadPool::PThread::join() |
428 | 5.72k | { |
429 | 5.72k | if( m_joinable ) |
430 | 5.72k | { |
431 | 5.72k | m_joinable = false; |
432 | 5.72k | pthread_join( m_id, nullptr ); |
433 | 5.72k | } |
434 | 5.72k | } |
435 | | |
436 | | #endif // HAVE_PTHREADS |
437 | | |
438 | | } // namespace vvenc |
439 | | |
440 | | //! \} |
441 | | |