dispatch_source_mach.cc 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. #include "base/mac/dispatch_source_mach.h"
  5. namespace base {
  6. DispatchSourceMach::DispatchSourceMach(const char* name,
  7. mach_port_t port,
  8. void (^event_handler)())
  9. : DispatchSourceMach(dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL),
  10. port,
  11. event_handler) {
  12. // Since the queue was created above in the delegated constructor, and it was
  13. // subsequently retained, release it here.
  14. dispatch_release(queue_);
  15. }
  16. DispatchSourceMach::DispatchSourceMach(dispatch_queue_t queue,
  17. mach_port_t port,
  18. void (^event_handler)())
  19. : queue_(queue, base::scoped_policy::RETAIN),
  20. source_(dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV,
  21. port, 0, queue_)),
  22. source_canceled_(dispatch_semaphore_create(0)) {
  23. dispatch_source_set_event_handler(source_, event_handler);
  24. dispatch_source_set_cancel_handler(source_, ^{
  25. dispatch_semaphore_signal(source_canceled_);
  26. });
  27. }
  28. DispatchSourceMach::~DispatchSourceMach() {
  29. // Cancel the source and wait for the semaphore to be signaled. This will
  30. // ensure the source managed by this class is not used after it is freed.
  31. dispatch_source_cancel(source_);
  32. source_.reset();
  33. dispatch_semaphore_wait(source_canceled_, DISPATCH_TIME_FOREVER);
  34. }
  35. void DispatchSourceMach::Resume() {
  36. dispatch_resume(source_);
  37. }
  38. } // namespace base