dispatch_source_mach.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2014 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_MAC_DISPATCH_SOURCE_MACH_H_
  5. #define BASE_MAC_DISPATCH_SOURCE_MACH_H_
  6. #include <dispatch/dispatch.h>
  7. #include "base/base_export.h"
  8. #include "base/mac/scoped_dispatch_object.h"
  9. #include "base/macros.h"
  10. namespace base {
  11. // This class encapsulates a MACH_RECV dispatch source. When this object is
  12. // destroyed, the source will be cancelled and it will wait for the source
  13. // to stop executing work. The source can run on either a user-supplied queue,
  14. // or it can create its own for the source.
  15. class BASE_EXPORT DispatchSourceMach {
  16. public:
  17. // Creates a new dispatch source for the |port| and schedules it on a new
  18. // queue that will be created with |name|. When a Mach message is received,
  19. // the |event_handler| will be called.
  20. DispatchSourceMach(const char* name,
  21. mach_port_t port,
  22. void (^event_handler)());
  23. // Creates a new dispatch source with the same semantics as above, but rather
  24. // than creating a new queue, it schedules the source on |queue|.
  25. DispatchSourceMach(dispatch_queue_t queue,
  26. mach_port_t port,
  27. void (^event_handler)());
  28. // Cancels the source and waits for it to become fully cancelled before
  29. // releasing the source.
  30. ~DispatchSourceMach();
  31. // Resumes the source. This must be called before any Mach messages will
  32. // be received.
  33. void Resume();
  34. dispatch_queue_t queue() const { return queue_.get(); }
  35. private:
  36. // The dispatch queue used to service the source_.
  37. ScopedDispatchObject<dispatch_queue_t> queue_;
  38. // A MACH_RECV dispatch source.
  39. ScopedDispatchObject<dispatch_source_t> source_;
  40. // Semaphore used to wait on the |source_|'s cancellation in the destructor.
  41. ScopedDispatchObject<dispatch_semaphore_t> source_canceled_;
  42. DISALLOW_COPY_AND_ASSIGN(DispatchSourceMach);
  43. };
  44. } // namespace base
  45. #endif // BASE_MAC_DISPATCH_SOURCE_MACH_H_