diff options
author | deanm@google.com <deanm@google.com@0039d316-1c4b-4281-b951-d872f2087c98> | 2008-09-02 11:15:48 +0000 |
---|---|---|
committer | deanm@google.com <deanm@google.com@0039d316-1c4b-4281-b951-d872f2087c98> | 2008-09-02 11:15:48 +0000 |
commit | a89d97fdbea8bf1e246f2adf33819342f684d944 (patch) | |
tree | 8f46b5c03c99276e6f35521127424134f0a79e17 /base/simple_thread.cc | |
parent | 5f6eee53a4ba6995b68a8ec6f22d3281529060c8 (diff) | |
download | chromium_src-a89d97fdbea8bf1e246f2adf33819342f684d944.zip chromium_src-a89d97fdbea8bf1e246f2adf33819342f684d944.tar.gz chromium_src-a89d97fdbea8bf1e246f2adf33819342f684d944.tar.bz2 |
Add a simple thread pool to SimpleThread.
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@1634 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'base/simple_thread.cc')
-rw-r--r-- | base/simple_thread.cc | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/base/simple_thread.cc b/base/simple_thread.cc index fa9a723..f919562 100644 --- a/base/simple_thread.cc +++ b/base/simple_thread.cc @@ -49,4 +49,70 @@ void DelegateSimpleThread::Run() { delegate_ = NULL; } +DelegateSimpleThreadPool::~DelegateSimpleThreadPool() { + DCHECK(threads_.empty()); + DCHECK(delegates_.empty()); + DCHECK(!dry_.IsSignaled()); +} + +void DelegateSimpleThreadPool::Start() { + DCHECK(threads_.empty()) << "Start() called with outstanding threads."; + for (int i = 0; i < num_threads_; ++i) { + DelegateSimpleThread* thread = new DelegateSimpleThread(this, name_prefix_); + thread->Start(); + threads_.push_back(thread); + } +} + +void DelegateSimpleThreadPool::JoinAll() { + DCHECK(!threads_.empty()) << "JoinAll() called with no outstanding threads."; + + // Tell all our threads to quit their worker loop. + AddWork(NULL, num_threads_); + + // Join and destroy all the worker threads. + for (int i = 0; i < num_threads_; ++i) { + threads_[i]->Join(); + delete threads_[i]; + } + threads_.clear(); + DCHECK(delegates_.empty()); +} + +void DelegateSimpleThreadPool::AddWork(Delegate* delegate, int repeat_count) { + AutoLock locked(lock_); + for (int i = 0; i < repeat_count; ++i) + delegates_.push(delegate); + // If we were empty, signal that we have work now. + if (!dry_.IsSignaled()) + dry_.Signal(); +} + +void DelegateSimpleThreadPool::Run() { + Delegate* work; + + while (true) { + dry_.Wait(); + { + AutoLock locked(lock_); + if (!dry_.IsSignaled()) + continue; + + DCHECK(!delegates_.empty()); + work = delegates_.front(); + delegates_.pop(); + + // Signal to any other threads that we're currently out of work. + if (delegates_.empty()) + dry_.Reset(); + } + + // A NULL delegate pointer signals us to quit. + if (!work) + break; + + work->Run(); + } +} + } // namespace base |