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