• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "base/task/thread_pool/worker_thread_set.h"
6 
7 #include "base/check_op.h"
8 #include "base/containers/contains.h"
9 #include "base/ranges/algorithm.h"
10 #include "base/task/thread_pool/worker_thread.h"
11 
12 namespace base::internal {
13 
operator ()(const WorkerThread * a,const WorkerThread * b) const14 bool WorkerThreadSet::Compare::operator()(const WorkerThread* a,
15                                           const WorkerThread* b) const {
16   return a->sequence_num() < b->sequence_num();
17 }
18 
19 WorkerThreadSet::WorkerThreadSet() = default;
20 
21 WorkerThreadSet::~WorkerThreadSet() = default;
22 
Insert(WorkerThread * worker)23 void WorkerThreadSet::Insert(WorkerThread* worker) {
24   DCHECK(!Contains(worker)) << "WorkerThread already on stack";
25   auto old_first = set_.begin();
26   set_.insert(worker);
27   if (worker != *set_.begin())
28     worker->BeginUnusedPeriod();
29   else if (old_first != set_.end())
30     (*old_first)->BeginUnusedPeriod();
31 }
32 
Take()33 WorkerThread* WorkerThreadSet::Take() {
34   if (IsEmpty())
35     return nullptr;
36   WorkerThread* const worker = *set_.begin();
37   set_.erase(set_.begin());
38   if (!IsEmpty())
39     (*set_.begin())->EndUnusedPeriod();
40   return worker;
41 }
42 
Peek() const43 WorkerThread* WorkerThreadSet::Peek() const {
44   if (IsEmpty())
45     return nullptr;
46   return *set_.begin();
47 }
48 
Contains(const WorkerThread * worker) const49 bool WorkerThreadSet::Contains(const WorkerThread* worker) const {
50   return set_.count(const_cast<WorkerThread*>(worker)) > 0;
51 }
52 
Remove(const WorkerThread * worker)53 void WorkerThreadSet::Remove(const WorkerThread* worker) {
54   DCHECK(!IsEmpty());
55   DCHECK_NE(worker, *set_.begin());
56   auto it = set_.find(const_cast<WorkerThread*>(worker));
57   CHECK(it != set_.end(), base::NotFatalUntil::M125);
58   DCHECK_NE(TimeTicks(), (*it)->GetLastUsedTime());
59   set_.erase(it);
60 }
61 
62 }  // namespace base::internal
63