OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 The Crashpad Authors. All rights reserved. |
| 2 // |
| 3 // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 // you may not use this file except in compliance with the License. |
| 5 // You may obtain a copy of the License at |
| 6 // |
| 7 // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 // |
| 9 // Unless required by applicable law or agreed to in writing, software |
| 10 // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 // See the License for the specific language governing permissions and |
| 13 // limitations under the License. |
| 14 |
| 15 #include "util/thread/worker_thread.h" |
| 16 |
| 17 #include "base/logging.h" |
| 18 #include "util/synchronization/semaphore.h" |
| 19 #include "util/thread/thread.h" |
| 20 |
| 21 namespace crashpad { |
| 22 |
| 23 namespace internal { |
| 24 |
| 25 class WorkerThreadImpl final : public Thread { |
| 26 public: |
| 27 WorkerThreadImpl(WorkerThread* self, double initial_work_delay) |
| 28 : semaphore_(0), |
| 29 initial_work_delay_(initial_work_delay), |
| 30 self_(self) {} |
| 31 ~WorkerThreadImpl() {} |
| 32 |
| 33 void ThreadMain() override { |
| 34 if (initial_work_delay_ > 0) |
| 35 semaphore_.TimedWait(initial_work_delay_); |
| 36 |
| 37 while (self_->running_) { |
| 38 self_->delegate_->DoWork(self_); |
| 39 semaphore_.TimedWait(self_->work_interval_); |
| 40 } |
| 41 } |
| 42 |
| 43 void SignalSemaphore() { |
| 44 semaphore_.Signal(); |
| 45 } |
| 46 |
| 47 private: |
| 48 // TODO(mark): Use a condition variable instead? |
| 49 Semaphore semaphore_; |
| 50 double initial_work_delay_; |
| 51 WorkerThread* self_; // Weak, owns this. |
| 52 }; |
| 53 |
| 54 } // namespace internal |
| 55 |
| 56 WorkerThread::WorkerThread(double work_interval, |
| 57 WorkerThread::Delegate* delegate) |
| 58 : work_interval_(work_interval), |
| 59 delegate_(delegate), |
| 60 impl_(), |
| 61 running_(false) {} |
| 62 |
| 63 WorkerThread::~WorkerThread() { |
| 64 DCHECK(!running_); |
| 65 } |
| 66 |
| 67 void WorkerThread::Start(double initial_work_delay) { |
| 68 DCHECK(!impl_); |
| 69 DCHECK(!running_); |
| 70 |
| 71 running_ = true; |
| 72 impl_.reset(new internal::WorkerThreadImpl(this, initial_work_delay)); |
| 73 impl_->Start(); |
| 74 } |
| 75 |
| 76 void WorkerThread::Stop() { |
| 77 DCHECK(running_); |
| 78 DCHECK(impl_); |
| 79 |
| 80 if (!running_) |
| 81 return; |
| 82 |
| 83 running_ = false; |
| 84 |
| 85 impl_->SignalSemaphore(); |
| 86 impl_->Join(); |
| 87 impl_.reset(); |
| 88 } |
| 89 |
| 90 void WorkerThread::DoWorkNow() { |
| 91 DCHECK(running_); |
| 92 impl_->SignalSemaphore(); |
| 93 } |
| 94 |
| 95 } // namespace crashpad |
OLD | NEW |