1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/child/worker_thread_impl.h"
7 #include "base/lazy_instance.h"
8 #include "base/logging.h"
9 #include "base/observer_list.h"
10 #include "base/threading/thread_local.h"
11 #include "content/child/worker_task_runner.h"
12 #include "content/common/content_export.h"
13 #include "content/public/child/worker_thread.h"
19 using WorkerThreadObservers
= base::ObserverList
<WorkerThread::Observer
>;
20 using ThreadLocalWorkerThreadObservers
=
21 base::ThreadLocalPointer
<WorkerThreadObservers
>;
23 // Stores a WorkerThreadObservers instance per thread.
24 base::LazyInstance
<ThreadLocalWorkerThreadObservers
> g_observers_tls
=
25 LAZY_INSTANCE_INITIALIZER
;
32 int WorkerThread::GetCurrentId() {
33 if (!g_observers_tls
.Get().Get())
35 return base::PlatformThread::CurrentId();
39 void WorkerThread::PostTask(int id
, const base::Closure
& task
) {
40 WorkerTaskRunner::Instance()->PostTask(id
, task
);
44 void WorkerThread::AddObserver(Observer
* observer
) {
45 DCHECK(GetCurrentId() > 0);
46 WorkerThreadObservers
* observers
= g_observers_tls
.Get().Get();
48 observers
->AddObserver(observer
);
52 void WorkerThread::RemoveObserver(Observer
* observer
) {
53 DCHECK(GetCurrentId() > 0);
54 WorkerThreadObservers
* observers
= g_observers_tls
.Get().Get();
56 observers
->RemoveObserver(observer
);
62 void WorkerThreadImpl::DidStartCurrentWorkerThread() {
63 ThreadLocalWorkerThreadObservers
& observers_tls
= g_observers_tls
.Get();
64 DCHECK(!observers_tls
.Get());
65 observers_tls
.Set(new WorkerThreadObservers());
69 void WorkerThreadImpl::WillStopCurrentWorkerThread() {
70 ThreadLocalWorkerThreadObservers
& observers_tls
= g_observers_tls
.Get();
71 WorkerThreadObservers
* observers
= observers_tls
.Get();
73 FOR_EACH_OBSERVER(WorkerThread::Observer
, *observers
,
74 WillStopCurrentWorkerThread());
76 observers_tls
.Set(nullptr);
79 } // namespace content