summaryrefslogtreecommitdiffstats
path: root/media/audio/scoped_loop_observer.cc
blob: 01187ec8f991be37bad58a9cf648c7be72ed5786 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/audio/scoped_loop_observer.h"

#include "base/bind.h"
#include "base/synchronization/waitable_event.h"

namespace media {

ScopedLoopObserver::ScopedLoopObserver(
    const scoped_refptr<base::MessageLoopProxy>& loop)
    : loop_(loop) {
  ObserveLoopDestruction(true, NULL);
}

ScopedLoopObserver::~ScopedLoopObserver() {
  ObserveLoopDestruction(false, NULL);
}

void ScopedLoopObserver::ObserveLoopDestruction(bool enable,
                                                base::WaitableEvent* done) {
  // Note: |done| may be NULL.
  if (loop_->BelongsToCurrentThread()) {
    base::MessageLoop* loop = base::MessageLoop::current();
    if (enable) {
      loop->AddDestructionObserver(this);
    } else {
      loop->RemoveDestructionObserver(this);
    }
  } else {
    base::WaitableEvent event(false, false);
    if (loop_->PostTask(FROM_HERE,
            base::Bind(&ScopedLoopObserver::ObserveLoopDestruction,
                       base::Unretained(this), enable, &event))) {
      event.Wait();
    } else {
      // The message loop's thread has already terminated, so no need to wait.
    }
  }

  if (done)
    done->Signal();
}

}  // namespace media.