Line data Source code
1 : /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 : /* vim:set ts=2 sw=2 sts=2 et cindent: */
3 : /* This Source Code Form is subject to the terms of the Mozilla Public
4 : * License, v. 2.0. If a copy of the MPL was not distributed with this
5 : * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 :
7 : #include "nsCache.h"
8 : #include "nsCacheUtils.h"
9 : #include "nsThreadUtils.h"
10 :
11 : using namespace mozilla;
12 :
13 0 : class nsDestroyThreadEvent : public Runnable {
14 : public:
15 0 : explicit nsDestroyThreadEvent(nsIThread* thread)
16 0 : : mozilla::Runnable("nsDestroyThreadEvent")
17 0 : , mThread(thread)
18 0 : {}
19 0 : NS_IMETHOD Run() override
20 : {
21 0 : mThread->Shutdown();
22 0 : return NS_OK;
23 : }
24 : private:
25 : nsCOMPtr<nsIThread> mThread;
26 : };
27 :
28 0 : nsShutdownThread::nsShutdownThread(nsIThread* aThread)
29 : : mozilla::Runnable("nsShutdownThread")
30 : , mMonitor("nsShutdownThread.mMonitor")
31 : , mShuttingDown(false)
32 0 : , mThread(aThread)
33 : {
34 0 : }
35 :
36 0 : nsShutdownThread::~nsShutdownThread()
37 : {
38 0 : }
39 :
40 : nsresult
41 0 : nsShutdownThread::Shutdown(nsIThread *aThread)
42 : {
43 : nsresult rv;
44 0 : RefPtr<nsDestroyThreadEvent> ev = new nsDestroyThreadEvent(aThread);
45 0 : rv = NS_DispatchToMainThread(ev);
46 0 : if (NS_FAILED(rv)) {
47 0 : NS_WARNING("Dispatching event in nsShutdownThread::Shutdown failed!");
48 : }
49 0 : return rv;
50 : }
51 :
52 : nsresult
53 0 : nsShutdownThread::BlockingShutdown(nsIThread *aThread)
54 : {
55 : nsresult rv;
56 :
57 0 : RefPtr<nsShutdownThread> st = new nsShutdownThread(aThread);
58 0 : nsCOMPtr<nsIThread> workerThread;
59 :
60 0 : rv = NS_NewNamedThread("thread shutdown", getter_AddRefs(workerThread));
61 0 : if (NS_FAILED(rv)) {
62 0 : NS_WARNING("Can't create nsShutDownThread worker thread!");
63 0 : return rv;
64 : }
65 :
66 : {
67 0 : MonitorAutoLock mon(st->mMonitor);
68 0 : rv = workerThread->Dispatch(st, NS_DISPATCH_NORMAL);
69 0 : if (NS_FAILED(rv)) {
70 : NS_WARNING(
71 0 : "Dispatching event in nsShutdownThread::BlockingShutdown failed!");
72 : } else {
73 0 : st->mShuttingDown = true;
74 0 : while (st->mShuttingDown) {
75 0 : mon.Wait();
76 : }
77 : }
78 : }
79 :
80 0 : return Shutdown(workerThread);
81 : }
82 :
83 : NS_IMETHODIMP
84 0 : nsShutdownThread::Run()
85 : {
86 0 : MonitorAutoLock mon(mMonitor);
87 0 : mThread->Shutdown();
88 0 : mShuttingDown = false;
89 0 : mon.Notify();
90 0 : return NS_OK;
91 : }
|