1 // Copyright 2014 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/mac/dispatch_source_mach.h"
6
7 namespace base {
8
9 DispatchSourceMach::DispatchSourceMach(const char* name,
10 mach_port_t port,
11 void (^event_handler)())
12 : DispatchSourceMach(dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL),
13 port,
14 event_handler) {
15 // Since the queue was created above in the delegated constructor, and it was
16 // subsequently retained, release it here.
17 dispatch_release(queue_);
18 }
19
20 DispatchSourceMach::DispatchSourceMach(dispatch_queue_t queue,
21 mach_port_t port,
22 void (^event_handler)())
23 : queue_(queue, base::scoped_policy::RETAIN),
24 source_(dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV,
25 port, 0, queue_)),
26 source_canceled_(dispatch_semaphore_create(0)) {
27 dispatch_source_set_event_handler(source_, event_handler);
28 dispatch_source_set_cancel_handler(source_, ^{
29 dispatch_semaphore_signal(source_canceled_);
30 });
31 }
32
~DispatchSourceMach()33 DispatchSourceMach::~DispatchSourceMach() {
34 // Cancel the source and wait for the semaphore to be signaled. This will
35 // ensure the source managed by this class is not used after it is freed.
36 dispatch_source_cancel(source_);
37 source_.reset();
38
39 dispatch_semaphore_wait(source_canceled_, DISPATCH_TIME_FOREVER);
40 }
41
Resume()42 void DispatchSourceMach::Resume() {
43 dispatch_resume(source_);
44 }
45
46 } // namespace base
47