| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2012 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 | |
| 5 #include "base/mac/libdispatch_task_runner.h" | |
| 6 | |
| 7 #include <stdint.h> | |
| 8 | |
| 9 #include "base/callback.h" | |
| 10 | |
| 11 namespace base { | |
| 12 namespace mac { | |
| 13 | |
| 14 LibDispatchTaskRunner::LibDispatchTaskRunner(const char* name) | |
| 15 : queue_(dispatch_queue_create(name, NULL)), | |
| 16 queue_finalized_(base::WaitableEvent::ResetPolicy::AUTOMATIC, | |
| 17 base::WaitableEvent::InitialState::NOT_SIGNALED) { | |
| 18 dispatch_set_context(queue_, this); | |
| 19 dispatch_set_finalizer_f(queue_, &LibDispatchTaskRunner::Finalizer); | |
| 20 } | |
| 21 | |
| 22 bool LibDispatchTaskRunner::PostDelayedTask( | |
| 23 const tracked_objects::Location& from_here, | |
| 24 const Closure& task, | |
| 25 base::TimeDelta delay) { | |
| 26 if (!queue_) | |
| 27 return false; | |
| 28 | |
| 29 // The block runtime would implicitly copy the reference, not the object | |
| 30 // it's referencing. Copy the closure into block storage so it's available | |
| 31 // to run. | |
| 32 __block const Closure task_copy = task; | |
| 33 void(^run_task)(void) = ^{ | |
| 34 task_copy.Run(); | |
| 35 }; | |
| 36 | |
| 37 int64_t delay_nano = | |
| 38 delay.InMicroseconds() * base::Time::kNanosecondsPerMicrosecond; | |
| 39 if (delay_nano > 0) { | |
| 40 dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, delay_nano); | |
| 41 dispatch_after(time, queue_, run_task); | |
| 42 } else { | |
| 43 dispatch_async(queue_, run_task); | |
| 44 } | |
| 45 return true; | |
| 46 } | |
| 47 | |
| 48 bool LibDispatchTaskRunner::RunsTasksOnCurrentThread() const { | |
| 49 return queue_ == dispatch_get_current_queue(); | |
| 50 } | |
| 51 | |
| 52 bool LibDispatchTaskRunner::PostNonNestableDelayedTask( | |
| 53 const tracked_objects::Location& from_here, | |
| 54 const Closure& task, | |
| 55 base::TimeDelta delay) { | |
| 56 return PostDelayedTask(from_here, task, delay); | |
| 57 } | |
| 58 | |
| 59 void LibDispatchTaskRunner::Shutdown() { | |
| 60 dispatch_release(queue_); | |
| 61 queue_ = NULL; | |
| 62 queue_finalized_.Wait(); | |
| 63 } | |
| 64 | |
| 65 dispatch_queue_t LibDispatchTaskRunner::GetDispatchQueue() const { | |
| 66 return queue_; | |
| 67 } | |
| 68 | |
| 69 LibDispatchTaskRunner::~LibDispatchTaskRunner() { | |
| 70 if (queue_) { | |
| 71 dispatch_set_context(queue_, NULL); | |
| 72 dispatch_set_finalizer_f(queue_, NULL); | |
| 73 dispatch_release(queue_); | |
| 74 } | |
| 75 } | |
| 76 | |
| 77 void LibDispatchTaskRunner::Finalizer(void* context) { | |
| 78 LibDispatchTaskRunner* self = static_cast<LibDispatchTaskRunner*>(context); | |
| 79 self->queue_finalized_.Signal(); | |
| 80 } | |
| 81 | |
| 82 } // namespace mac | |
| 83 } // namespace base | |
| OLD | NEW |