• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef BASE_MAC_DISPATCH_SOURCE_MACH_H_
6 #define BASE_MAC_DISPATCH_SOURCE_MACH_H_
7 
8 #include <dispatch/dispatch.h>
9 
10 #include "base/base_export.h"
11 #include "base/mac/scoped_dispatch_object.h"
12 
13 namespace base {
14 
15 // This class encapsulates a MACH_RECV dispatch source. When this object is
16 // destroyed, the source will be cancelled and it will wait for the source
17 // to stop executing work. The source can run on either a user-supplied queue,
18 // or it can create its own for the source.
19 class BASE_EXPORT DispatchSourceMach {
20  public:
21   // Creates a new dispatch source for the |port| and schedules it on a new
22   // queue that will be created with |name|. When a Mach message is received,
23   // the |event_handler| will be called.
24   DispatchSourceMach(const char* name,
25                      mach_port_t port,
26                      void (^event_handler)());
27 
28   // Creates a new dispatch source with the same semantics as above, but rather
29   // than creating a new queue, it schedules the source on |queue|.
30   DispatchSourceMach(dispatch_queue_t queue,
31                      mach_port_t port,
32                      void (^event_handler)());
33 
34   DispatchSourceMach(const DispatchSourceMach&) = delete;
35   DispatchSourceMach& operator=(const DispatchSourceMach&) = delete;
36 
37   // Cancels the source and waits for it to become fully cancelled before
38   // releasing the source.
39   ~DispatchSourceMach();
40 
41   // Resumes the source. This must be called before any Mach messages will
42   // be received.
43   void Resume();
44 
queue()45   dispatch_queue_t queue() const { return queue_.get(); }
46 
47  private:
48   // The dispatch queue used to service the source_.
49   ScopedDispatchObject<dispatch_queue_t> queue_;
50 
51   // A MACH_RECV dispatch source.
52   ScopedDispatchObject<dispatch_source_t> source_;
53 
54   // Semaphore used to wait on the |source_|'s cancellation in the destructor.
55   ScopedDispatchObject<dispatch_semaphore_t> source_canceled_;
56 };
57 
58 }  // namespace base
59 
60 #endif  // BASE_MAC_DISPATCH_SOURCE_MACH_H_
61