xref: /aosp_15_r20/external/cronet/base/task/thread_pool/worker_thread_set.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2016 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_TASK_THREAD_POOL_WORKER_THREAD_SET_H_
6 #define BASE_TASK_THREAD_POOL_WORKER_THREAD_SET_H_
7 
8 #include <stddef.h>
9 
10 #include <set>
11 
12 #include "base/base_export.h"
13 #include "base/memory/raw_ptr.h"
14 
15 namespace base {
16 namespace internal {
17 
18 class WorkerThreadWaitableEvent;
19 
20 // An ordered set of WorkerThreads which has custom logic to treat the worker at
21 // the front of the set as being "in-use" (so its time in that position doesn't
22 // count towards being inactive / reclaimable). Supports removal of arbitrary
23 // WorkerThreads. DCHECKs when a WorkerThread is inserted multiple times.
24 // WorkerThreads are not owned by the set. All operations are amortized
25 // O(log(n)). This class is NOT thread-safe.
26 class BASE_EXPORT WorkerThreadSet {
27   struct Compare {
28     bool operator()(const WorkerThreadWaitableEvent* a,
29                     const WorkerThreadWaitableEvent* b) const;
30   };
31 
32  public:
33   WorkerThreadSet();
34   WorkerThreadSet(const WorkerThreadSet&) = delete;
35   WorkerThreadSet& operator=(const WorkerThreadSet&) = delete;
36   ~WorkerThreadSet();
37 
38   // Inserts |worker| in the set. |worker| must not already be on the set. Flags
39   // the WorkerThreadWaitableEvent previously at the front of the set, if it
40   // changed, or |worker| as unused.
41   void Insert(WorkerThreadWaitableEvent* worker);
42 
43   // Removes the front WorkerThread from the set and returns it. Returns nullptr
44   // if the set is empty. Flags the WorkerThread now at the front of the set, if
45   // any, as being in-use.
46   WorkerThreadWaitableEvent* Take();
47 
48   // Returns the front WorkerThread from the set, nullptr if empty.
49   WorkerThreadWaitableEvent* Peek() const;
50 
51   // Returns true if |worker| is already in the set.
52   bool Contains(const WorkerThreadWaitableEvent* worker) const;
53 
54   // Removes |worker| from the set. Must not be invoked for the first worker
55   // on the set.
56   void Remove(const WorkerThreadWaitableEvent* worker);
57 
58   // Returns the number of WorkerThreads on the set.
Size()59   size_t Size() const { return set_.size(); }
60 
61   // Returns true if the set is empty.
IsEmpty()62   bool IsEmpty() const { return set_.empty(); }
63 
64  private:
65   std::set<raw_ptr<WorkerThreadWaitableEvent, SetExperimental>, Compare> set_;
66 };
67 
68 }  // namespace internal
69 }  // namespace base
70 
71 #endif  // BASE_TASK_THREAD_POOL_WORKER_THREAD_SET_H_
72