nsCacheUtils.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. #include "nsCache.h"
  7. #include "nsCacheUtils.h"
  8. #include "nsThreadUtils.h"
  9. using namespace mozilla;
  10. class nsDestroyThreadEvent : public Runnable {
  11. public:
  12. explicit nsDestroyThreadEvent(nsIThread *thread)
  13. : mThread(thread)
  14. {}
  15. NS_IMETHOD Run() override
  16. {
  17. mThread->Shutdown();
  18. return NS_OK;
  19. }
  20. private:
  21. nsCOMPtr<nsIThread> mThread;
  22. };
  23. nsShutdownThread::nsShutdownThread(nsIThread *aThread)
  24. : mMonitor("nsShutdownThread.mMonitor")
  25. , mShuttingDown(false)
  26. , mThread(aThread)
  27. {
  28. }
  29. nsShutdownThread::~nsShutdownThread()
  30. {
  31. }
  32. nsresult
  33. nsShutdownThread::Shutdown(nsIThread *aThread)
  34. {
  35. nsresult rv;
  36. RefPtr<nsDestroyThreadEvent> ev = new nsDestroyThreadEvent(aThread);
  37. rv = NS_DispatchToMainThread(ev);
  38. if (NS_FAILED(rv)) {
  39. NS_WARNING("Dispatching event in nsShutdownThread::Shutdown failed!");
  40. }
  41. return rv;
  42. }
  43. nsresult
  44. nsShutdownThread::BlockingShutdown(nsIThread *aThread)
  45. {
  46. nsresult rv;
  47. RefPtr<nsShutdownThread> st = new nsShutdownThread(aThread);
  48. nsCOMPtr<nsIThread> workerThread;
  49. rv = NS_NewNamedThread("thread shutdown", getter_AddRefs(workerThread));
  50. if (NS_FAILED(rv)) {
  51. NS_WARNING("Can't create nsShutDownThread worker thread!");
  52. return rv;
  53. }
  54. {
  55. MonitorAutoLock mon(st->mMonitor);
  56. rv = workerThread->Dispatch(st, NS_DISPATCH_NORMAL);
  57. if (NS_FAILED(rv)) {
  58. NS_WARNING(
  59. "Dispatching event in nsShutdownThread::BlockingShutdown failed!");
  60. } else {
  61. st->mShuttingDown = true;
  62. while (st->mShuttingDown) {
  63. mon.Wait();
  64. }
  65. }
  66. }
  67. return Shutdown(workerThread);
  68. }
  69. NS_IMETHODIMP
  70. nsShutdownThread::Run()
  71. {
  72. MonitorAutoLock mon(mMonitor);
  73. mThread->Shutdown();
  74. mShuttingDown = false;
  75. mon.Notify();
  76. return NS_OK;
  77. }