Coverage Report

Created: 2026-12-01 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/vvenc/source/Lib/Utilities/NoMallocThreadPool.h
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
/** \file     NoMallocThreadPool.h
43
    \brief    thread pool
44
*/
45
46
#pragma once
47
48
#include <thread>
49
#include <mutex>
50
#include <condition_variable>
51
#include <atomic>
52
#include <chrono>
53
#include <array>
54
55
#ifdef HAVE_PTHREADS
56
#include <pthread.h>
57
#endif
58
59
#include "CommonLib/CommonDef.h"
60
#if ENABLE_TIME_PROFILING_MT_MODE
61
#include "CommonLib/TimeProfiler.h"
62
#endif
63
64
//! \ingroup Utilities
65
//! \{
66
67
namespace vvenc {
68
69
#ifdef TRACE_ENABLE_ITT
70
static __itt_domain* itt_domain_thrd = __itt_domain_create( "Threading" );
71
72
static __itt_string_handle* itt_handle_TPspinWait = __itt_string_handle_create( "Spin_Wait" );
73
static __itt_string_handle* itt_handle_TPblocked  = __itt_string_handle_create( "Blocked" );
74
static __itt_string_handle* itt_handle_TPaddTask  = __itt_string_handle_create( "Add_Task" );
75
76
//static long itt_TP_blocked = 1;
77
78
#endif //TRACE_ENABLE_ITT
79
80
#if ENABLE_VALGRIND_CODE
81
typedef std::unique_lock< std::mutex > MutexLock;
82
#endif
83
84
// the idle thread that looks for work (the owner of m_idleMutex) sleeps after busy-waiting this long without
85
// finding one; the other idle threads wait for the mutex
86
154
const static auto BUSY_WAIT_TIME = [] {
87
154
  const char *env = getenv( "BUSY_WAIT_TIME" );
88
154
  if( env )
89
0
    return std::chrono::milliseconds( atoi( env ) );
90
154
  return std::chrono::milliseconds( 1 );
91
154
}();
vvencimpl.cpp:vvenc::$_0::operator()() const
Line
Count
Source
86
14
const static auto BUSY_WAIT_TIME = [] {
87
14
  const char *env = getenv( "BUSY_WAIT_TIME" );
88
14
  if( env )
89
0
    return std::chrono::milliseconds( atoi( env ) );
90
14
  return std::chrono::milliseconds( 1 );
91
14
}();
EncLib.cpp:vvenc::$_0::operator()() const
Line
Count
Source
86
14
const static auto BUSY_WAIT_TIME = [] {
87
14
  const char *env = getenv( "BUSY_WAIT_TIME" );
88
14
  if( env )
89
0
    return std::chrono::milliseconds( atoi( env ) );
90
14
  return std::chrono::milliseconds( 1 );
91
14
}();
NoMallocThreadPool.cpp:vvenc::$_0::operator()() const
Line
Count
Source
86
14
const static auto BUSY_WAIT_TIME = [] {
87
14
  const char *env = getenv( "BUSY_WAIT_TIME" );
88
14
  if( env )
89
0
    return std::chrono::milliseconds( atoi( env ) );
90
14
  return std::chrono::milliseconds( 1 );
91
14
}();
MCTF.cpp:vvenc::$_0::operator()() const
Line
Count
Source
86
14
const static auto BUSY_WAIT_TIME = [] {
87
14
  const char *env = getenv( "BUSY_WAIT_TIME" );
88
14
  if( env )
89
0
    return std::chrono::milliseconds( atoi( env ) );
90
14
  return std::chrono::milliseconds( 1 );
91
14
}();
CuTree.cpp:vvenc::$_0::operator()() const
Line
Count
Source
86
14
const static auto BUSY_WAIT_TIME = [] {
87
14
  const char *env = getenv( "BUSY_WAIT_TIME" );
88
14
  if( env )
89
0
    return std::chrono::milliseconds( atoi( env ) );
90
14
  return std::chrono::milliseconds( 1 );
91
14
}();
EncGOP.cpp:vvenc::$_0::operator()() const
Line
Count
Source
86
14
const static auto BUSY_WAIT_TIME = [] {
87
14
  const char *env = getenv( "BUSY_WAIT_TIME" );
88
14
  if( env )
89
0
    return std::chrono::milliseconds( atoi( env ) );
90
14
  return std::chrono::milliseconds( 1 );
91
14
}();
EncPicture.cpp:vvenc::$_0::operator()() const
Line
Count
Source
86
14
const static auto BUSY_WAIT_TIME = [] {
87
14
  const char *env = getenv( "BUSY_WAIT_TIME" );
88
14
  if( env )
89
0
    return std::chrono::milliseconds( atoi( env ) );
90
14
  return std::chrono::milliseconds( 1 );
91
14
}();
EncSlice.cpp:vvenc::$_0::operator()() const
Line
Count
Source
86
14
const static auto BUSY_WAIT_TIME = [] {
87
14
  const char *env = getenv( "BUSY_WAIT_TIME" );
88
14
  if( env )
89
0
    return std::chrono::milliseconds( atoi( env ) );
90
14
  return std::chrono::milliseconds( 1 );
91
14
}();
EncAdaptiveLoopFilter.cpp:vvenc::$_0::operator()() const
Line
Count
Source
86
14
const static auto BUSY_WAIT_TIME = [] {
87
14
  const char *env = getenv( "BUSY_WAIT_TIME" );
88
14
  if( env )
89
0
    return std::chrono::milliseconds( atoi( env ) );
90
14
  return std::chrono::milliseconds( 1 );
91
14
}();
EncCu.cpp:vvenc::$_0::operator()() const
Line
Count
Source
86
14
const static auto BUSY_WAIT_TIME = [] {
87
14
  const char *env = getenv( "BUSY_WAIT_TIME" );
88
14
  if( env )
89
0
    return std::chrono::milliseconds( atoi( env ) );
90
14
  return std::chrono::milliseconds( 1 );
91
14
}();
IntraSearch.cpp:vvenc::$_0::operator()() const
Line
Count
Source
86
14
const static auto BUSY_WAIT_TIME = [] {
87
14
  const char *env = getenv( "BUSY_WAIT_TIME" );
88
14
  if( env )
89
0
    return std::chrono::milliseconds( atoi( env ) );
90
14
  return std::chrono::milliseconds( 1 );
91
14
}();
92
93
94
// enable this if tasks need to be added from mutliple threads
95
#define ADD_TASK_THREAD_SAFE 1
96
97
98
// ---------------------------------------------------------------------------
99
// Synchronization tools
100
// ---------------------------------------------------------------------------
101
102
struct Barrier
103
{
104
  void unlock()
105
1.43k
  {
106
1.43k
    m_lockState.store( false );
107
1.43k
  }
108
109
  void lock()
110
4.65k
  {
111
4.65k
    m_lockState.store( true );
112
4.65k
  }
113
114
  bool isBlocked() const
115
6.30M
  {
116
6.30M
    return m_lockState;
117
6.30M
  }
118
119
  Barrier()  = default;
120
  ~Barrier() = default;
121
5.72k
  explicit Barrier( bool locked ) : m_lockState( locked ) {}
122
123
  Barrier( const Barrier & ) = delete;
124
  Barrier( Barrier && )      = delete;
125
126
  Barrier& operator=( const Barrier & ) = delete;
127
  Barrier& operator=( Barrier && )      = delete;
128
129
private:
130
  std::atomic_bool m_lockState{ true };
131
};
132
133
struct BlockingBarrier
134
{
135
  void unlock()
136
0
  {
137
0
    std::unique_lock<std::mutex> l( m_lock );
138
0
    m_intBarrier.unlock();
139
0
    if( !m_intBarrier.isBlocked() )
140
0
    {
141
0
      m_cond.notify_all();
142
0
    }
143
0
  }
144
145
  void lock()
146
0
  {
147
0
    std::unique_lock<std::mutex> l( m_lock );
148
0
    m_intBarrier.lock();
149
0
  }
150
151
  bool isBlocked() const
152
0
  {
153
0
    return m_intBarrier.isBlocked();
154
0
  }
155
156
  void wait() const
157
0
  {
158
0
    BlockingBarrier* nonconst = const_cast<BlockingBarrier*>(this);
159
0
160
0
    std::unique_lock<std::mutex> l( nonconst->m_lock );
161
0
    nonconst->m_cond.wait( l, [this] { return !m_intBarrier.isBlocked(); } );
162
0
  }
163
164
  BlockingBarrier()  = default;
165
0
  ~BlockingBarrier() { std::unique_lock<std::mutex> l( m_lock ); } // ensure all threads have unlocked the mutex, when we start destruction
166
167
  BlockingBarrier( const BlockingBarrier& ) = delete;
168
  BlockingBarrier( BlockingBarrier&& )      = delete;
169
170
  BlockingBarrier& operator=( const BlockingBarrier& ) = delete;
171
  BlockingBarrier& operator=( BlockingBarrier&& ) = delete;
172
173
  // cast to const ref Barrier, so we can use it for thread pool tasks:
174
0
  operator const Barrier&() const { return m_intBarrier; }
175
176
private:
177
  Barrier                 m_intBarrier;
178
  std::condition_variable m_cond;
179
  std::mutex              m_lock;
180
};
181
182
struct WaitCounter
183
{
184
  int operator++()
185
4.65k
  {
186
4.65k
    std::unique_lock<std::mutex> l( m_lock );
187
4.65k
    done.lock();
188
4.65k
    return ++m_count;
189
4.65k
  }
190
191
  int operator--()
192
4.65k
  {
193
4.65k
    std::unique_lock<std::mutex> l( m_lock );
194
4.65k
    const unsigned int new_count = --m_count;
195
4.65k
    if( new_count == 0 )
196
1.43k
    {
197
1.43k
      m_cond.notify_all();
198
1.43k
      done.unlock();
199
1.43k
    }
200
4.65k
    l.unlock(); // unlock mutex after done-barrier to prevent race between barrier and counter
201
4.65k
    return new_count;
202
4.65k
  }
203
204
  bool isBlocked() const
205
0
  {
206
    // take the lock: a caller that sees "not blocked" may at once reuse what the counted tasks read
207
0
    WaitCounter* nonconst = const_cast<WaitCounter*>( this );
208
0
    std::unique_lock<std::mutex> l( nonconst->m_lock );
209
0
    return 0 != m_count;
210
0
  }
211
212
  void wait() const
213
0
  {
214
0
    WaitCounter* nonconst = const_cast<WaitCounter*>(this);
215
216
0
    std::unique_lock<std::mutex> l( nonconst->m_lock );
217
0
    nonconst->m_cond.wait( l, [this] { return m_count == 0; } );
218
0
  }
219
220
5.72k
  WaitCounter() = default;
221
5.72k
  ~WaitCounter() { std::unique_lock<std::mutex> l( m_lock ); }   // ensure all threads have unlocked the mutex, when we start destruction
222
223
  WaitCounter( const WaitCounter & ) = delete;
224
  WaitCounter( WaitCounter && )      = delete;
225
226
  WaitCounter &operator=( const WaitCounter & ) = delete;
227
  WaitCounter &operator=( WaitCounter && )      = delete;
228
229
  Barrier done{ false };
230
231
private:
232
  std::condition_variable m_cond;
233
  std::mutex              m_lock;
234
  unsigned int            m_count = 0;
235
};
236
237
238
239
// ---------------------------------------------------------------------------
240
// Thread Pool
241
// ---------------------------------------------------------------------------
242
243
using CBarrierVec = std::vector<const Barrier*>;
244
245
class NoMallocThreadPool
246
{
247
  typedef enum
248
  {
249
    FREE = 0,
250
    PREPARING,
251
    WAITING,
252
    RUNNING
253
  } TaskState;
254
255
  using TaskFunc = bool ( * )( int, void * );
256
257
  struct Slot
258
  {
259
    TaskFunc               func      { nullptr };
260
    TaskFunc               readyCheck{ nullptr };
261
    void*                  param     { nullptr };
262
    WaitCounter*           counter   { nullptr };
263
    Barrier*               done      { nullptr };
264
    CBarrierVec            barriers;
265
    std::atomic<TaskState> state     { FREE };
266
    // lower = more urgent (see addBarrierTask); atomic because a scan may read it while the slot is being refilled
267
    std::atomic<int64_t>   priority  { 0 };
268
  };
269
270
271
  class ChunkedTaskQueue
272
  {
273
    constexpr static int ChunkSize = 128;
274
275
    class Chunk
276
    {
277
      std::array<Slot, ChunkSize> m_slots;
278
      std::atomic<Chunk*>         m_next{ nullptr };
279
      Chunk&                      m_firstChunk;
280
281
1.43k
      Chunk( Chunk* firstPtr ) : m_firstChunk{ *firstPtr } {}
282
283
      friend class ChunkedTaskQueue;
284
    };
285
286
  public:
287
    class Iterator
288
    {
289
      Slot*  m_slot  = nullptr;
290
      Chunk* m_chunk = nullptr;
291
292
    public:
293
8.03M
      Iterator() = default;
294
7.16k
      Iterator( Slot* slot, Chunk* chunk ) : m_slot( slot ), m_chunk( chunk ) {}
295
296
      Iterator& operator++()
297
0
      {
298
0
        CHECKD( m_slot == nullptr, "incrementing invalid iterator" );
299
0
        CHECKD( m_chunk == nullptr, "incrementing invalid iterator" );
300
301
0
        if( m_slot != &m_chunk->m_slots.back() )
302
0
        {
303
0
          ++m_slot;
304
0
        }
305
0
        else
306
0
        {
307
0
          m_chunk = m_chunk->m_next;
308
0
          if( m_chunk )
309
0
          {
310
0
            m_slot  = &m_chunk->m_slots.front();
311
0
          }
312
0
          else
313
0
          {
314
0
            m_slot  = nullptr;
315
0
          }
316
0
        }
317
0
        return *this;
318
0
      }
319
320
      // increment iterator and wrap around, if end is reached
321
      Iterator& incWrap()
322
1.02G
      {
323
1.02G
        CHECKD( m_slot == nullptr, "incrementing invalid iterator" );
324
1.02G
        CHECKD( m_chunk == nullptr, "incrementing invalid iterator" );
325
326
1.02G
        if( m_slot != &m_chunk->m_slots.back() )
327
1.01G
        {
328
1.01G
          ++m_slot;
329
1.01G
        }
330
7.98M
        else
331
7.98M
        {
332
7.98M
          if( (Chunk*)m_chunk->m_next )
333
0
          {
334
0
            m_chunk = m_chunk->m_next;
335
0
          }
336
7.98M
          else
337
7.98M
          {
338
7.98M
            m_chunk = &m_chunk->m_firstChunk;
339
7.98M
          }
340
7.98M
          m_slot = &m_chunk->m_slots.front();
341
7.98M
        }
342
1.02G
        return *this;
343
1.02G
      }
344
345
0
      bool operator==( const Iterator& rhs ) const { return m_slot == rhs.m_slot; } // don't need to compare m_chunk, because m_slot is a pointer
346
1.03G
      bool operator!=( const Iterator& rhs ) const { return m_slot != rhs.m_slot; } // don't need to compare m_chunk, because m_slot is a pointer
347
348
1.02G
      Slot& operator*() { return *m_slot; }
349
350
16.1M
      bool isValid() const { return m_slot != nullptr && m_chunk != nullptr; }
351
352
      using iterator_category = std::forward_iterator_tag;
353
      using value_type        = Slot;
354
      using pointer           = Slot*;
355
      using reference         = Slot&;
356
      using difference_type   = ptrdiff_t;
357
    };
358
359
1.43k
    ChunkedTaskQueue() = default;
360
    ~ChunkedTaskQueue()
361
1.43k
    {
362
1.43k
      Chunk* next = m_firstChunk.m_next;
363
1.43k
      while( next )
364
0
      {
365
0
        Chunk* curr = next;
366
0
        next = curr->m_next;
367
0
        delete curr;
368
0
      }
369
1.43k
    }
370
371
    ChunkedTaskQueue( const ChunkedTaskQueue& ) = delete;
372
    ChunkedTaskQueue( ChunkedTaskQueue&& )      = delete;
373
374
    // grow the queue by adding a chunk and return an iterator to the first new task-slot
375
    Iterator grow()
376
0
    {
377
0
      std::unique_lock<std::mutex> l( m_resizeMutex );  // prevent concurrent growth of the queue. Read access while growing is no problem
378
379
0
      m_lastChunk->m_next = new Chunk( &m_firstChunk );
380
0
      m_lastChunk         = m_lastChunk->m_next;
381
382
0
      return Iterator{ &m_lastChunk->m_slots.front(), m_lastChunk };
383
0
    }
384
385
7.16k
    Iterator begin() { return Iterator{ &m_firstChunk.m_slots.front(), &m_firstChunk }; }
386
0
    Iterator end()   { return Iterator{ nullptr, nullptr }; }
387
388
  private:
389
    Chunk  m_firstChunk{ &m_firstChunk };
390
    Chunk* m_lastChunk = &m_firstChunk;
391
392
    std::mutex m_resizeMutex;
393
  };
394
395
396
public:
397
  NoMallocThreadPool( int numThreads = 1, const char *threadPoolName = nullptr, const VVEncCfg* encCfg = nullptr );
398
  // For tests: how long the idle thread that looks for work busy-waits before it sleeps, and how long it sleeps at
399
  // most before it looks again (safety net).
400
  NoMallocThreadPool( int numThreads, const char *threadPoolName, const VVEncCfg* encCfg,
401
                      std::chrono::microseconds idleBusyWait, std::chrono::milliseconds safetyWakeInterval );
402
  ~NoMallocThreadPool();
403
404
  // A free thread takes the ready task with the lowest priority value. 0 (the default) is the most urgent: tasks the
405
  // caller waits for, such as the pre-analysis rows. A picture's CTU and finish tasks use 1 + the picture's start order
406
  // (Picture::encStartOrder), so the picture started first gets the threads first and frees its picture encoder soonest.
407
  // 64 bits, so that the start order never wraps. The order in which tasks run never changes the output.
408
  bool addBarrierTask( bool             ( *func )( int, void* ),
409
                       void*               param,
410
                       WaitCounter*        counter                    = nullptr,
411
                       Barrier*            done                       = nullptr,
412
                       const CBarrierVec&& barriers                   = {},
413
                       bool             ( *readyCheck )( int, void* ) = nullptr,
414
                       int64_t             priority                   = 0 )
415
7.51k
  {
416
7.51k
    if( m_threads.empty() )
417
0
    {
418
      // if singlethreaded, execute all pending tasks
419
0
      if( m_nextFillSlot != m_tasks.begin() )
420
0
      {
421
0
        processTasksOnMainThread();
422
0
      }
423
424
      // when no barriers block this task, execute it directly
425
0
      if( std::none_of( barriers.begin(), barriers.end(), []( const Barrier* b ) { return b && b->isBlocked(); } )
426
0
          && ( !readyCheck || readyCheck( 0, param ) ) )
427
0
      {
428
0
        if( func( 0, param ) )
429
0
        {
430
0
          if( done != nullptr )
431
0
          {
432
0
            done->unlock();
433
0
          }
434
0
          return true;
435
0
        }
436
0
      }
437
0
    }
438
439
7.51k
    while( true )
440
7.51k
    {
441
7.51k
#if ADD_TASK_THREAD_SAFE
442
7.51k
      std::unique_lock<std::mutex> l(m_nextFillSlotMutex);
443
7.51k
#endif
444
7.51k
      CHECKD( !m_nextFillSlot.isValid(), "Next fill slot iterator should always be valid" );
445
7.51k
      const auto startIt = m_nextFillSlot;
446
447
7.51k
#if ADD_TASK_THREAD_SAFE
448
7.51k
      l.unlock();
449
7.51k
#endif
450
451
7.51k
      bool first = true;
452
7.51k
      for( auto it = startIt; it != startIt || first; it.incWrap() )
453
7.51k
      {
454
#if ENABLE_VALGRIND_CODE
455
        MutexLock lock( m_extraMutex );
456
#endif
457
458
7.51k
        first = false;
459
460
7.51k
        auto& t = *it;
461
7.51k
        auto expected = FREE;
462
7.51k
        if( t.state.load( std::memory_order_relaxed ) == FREE && t.state.compare_exchange_strong( expected, PREPARING ) )
463
7.51k
        {
464
7.51k
          if( counter )
465
4.65k
          {
466
4.65k
            counter->operator++();
467
4.65k
          }
468
469
7.51k
          t.func       = func;
470
7.51k
          t.readyCheck = readyCheck;
471
7.51k
          t.param      = param;
472
7.51k
          t.done       = done;
473
7.51k
          t.counter    = counter;
474
7.51k
          t.barriers   = std::move( barriers );
475
7.51k
          t.priority.store( priority, std::memory_order_relaxed );   // published by the store of WAITING
476
7.51k
          t.state      = WAITING;
477
7.51k
          wakeIdleThread();
478
479
7.51k
#if ADD_TASK_THREAD_SAFE
480
7.51k
          l.lock();
481
7.51k
#endif
482
7.51k
          m_nextFillSlot.incWrap();
483
7.51k
          return true;
484
7.51k
        }
485
7.51k
      }
486
487
0
#if ADD_TASK_THREAD_SAFE
488
0
      l.lock();
489
0
#endif
490
0
      m_nextFillSlot = m_tasks.grow();
491
0
    }
492
0
    return false;
493
7.51k
  }
494
495
  bool processTasksOnMainThread();
496
497
  // For a task that makes other tasks ready before it returns: lets a sleeping idle thread look for them.
498
3.99k
  void signalProgress() { wakeIdleThread(); }
499
  // Wake-ups caught by the safety net: lost ones, or ones delayed longer than the safety interval by preemption of the
500
  // producer. 0 in the unit test, whose interval is long.
501
1.43k
  unsigned numWakeUpsMissed() const { return m_wakeUpsMissed.load( std::memory_order_relaxed ); }
502
503
  void shutdown( bool block );
504
  void waitForThreads();
505
506
1.43k
  int numThreads() const { return (int)m_threads.size(); }
507
#if ENABLE_TIME_PROFILING_MT_MODE
508
  const std::vector< TProfiler* >& getProfilers() { return profilers; }
509
#endif
510
511
private:
512
#ifdef HAVE_PTHREADS
513
  struct PThread
514
  {
515
    PThread()                            = default;
516
    ~PThread()                           = default;
517
518
    PThread( const PThread& )            = delete;
519
    PThread& operator=( const PThread& ) = delete;
520
521
4.29k
    PThread( PThread&& other ) { *this = std::move( other ); };
522
    PThread& operator=( PThread&& other );
523
524
    template<class TFunc, class... TArgs>
525
    PThread( TFunc&& func, TArgs&&... args );
526
527
11.4k
    bool joinable() { return m_joinable; }
528
    void join();
529
530
  private:
531
    pthread_t m_id       = 0;
532
    bool      m_joinable = false;
533
  };
534
#endif   // HAVE_PTHREADS
535
536
#if HAVE_PTHREADS
537
  using ThreadImpl = PThread;
538
#else
539
  using ThreadImpl = std::thread;
540
#endif
541
542
  using TaskIterator = ChunkedTaskQueue::Iterator;
543
544
  // members
545
  std::string               m_poolName;
546
  std::atomic_bool          m_exitThreads{ false };
547
  std::vector<ThreadImpl>   m_threads;
548
  ChunkedTaskQueue          m_tasks;
549
  TaskIterator              m_nextFillSlot = m_tasks.begin();
550
#if ADD_TASK_THREAD_SAFE
551
  std::mutex                m_nextFillSlotMutex;
552
#endif
553
  std::mutex                m_idleMutex;             // owned by the idle thread that looks for work
554
  std::chrono::microseconds m_idleBusyWait;          // how long that thread busy-waits before it sleeps
555
  std::chrono::milliseconds m_safetyWakeInterval;    // how long it sleeps at most before it looks again
556
  std::mutex                m_sleepMutex;
557
  std::condition_variable   m_sleepCond;
558
  std::atomic_bool          m_idleThreadSleeps{ false };
559
  std::atomic_uint          m_wakeUpsMissed{ 0 };    // safety-net timeouts after which work was found
560
#if ENABLE_VALGRIND_CODE
561
  std::mutex                m_extraMutex;
562
#endif
563
#if ENABLE_TIME_PROFILING_MT_MODE
564
  std::vector< TProfiler* > profilers;
565
#endif
566
567
  // internal functions
568
  void         threadProc  ( int threadId, const VVEncCfg& encCfg );
569
  TaskIterator findNextTask( int threadId, TaskIterator startSearch, bool* rescheduled = nullptr );
570
  TaskIterator waitForTask ( int threadId, TaskIterator startSearch );
571
  void         wakeIdleThread();
572
  bool         processTask ( int threadId, Slot& task );
573
};
574
575
} // namespace vvenc
576
577
//! \}
578