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.
5 #include "base/mac/libdispatch_task_runner.h"
7 #include "base/callback.h"
12 LibDispatchTaskRunner::LibDispatchTaskRunner(const char* name
)
13 : queue_(dispatch_queue_create(name
, NULL
)),
14 queue_finalized_(false, false) {
15 dispatch_set_context(queue_
, this);
16 dispatch_set_finalizer_f(queue_
, &LibDispatchTaskRunner::Finalizer
);
19 bool LibDispatchTaskRunner::PostDelayedTask(
20 const tracked_objects::Location
& from_here
,
22 base::TimeDelta delay
) {
26 // The block runtime would implicitly copy the reference, not the object
27 // it's referencing. Copy the closure into block storage so it's available
29 __block
const Closure task_copy
= task
;
30 void(^run_task
)(void) = ^{
35 delay
.InMicroseconds() * base::Time::kNanosecondsPerMicrosecond
;
37 dispatch_time_t time
= dispatch_time(DISPATCH_TIME_NOW
, delay_nano
);
38 dispatch_after(time
, queue_
, run_task
);
40 dispatch_async(queue_
, run_task
);
45 bool LibDispatchTaskRunner::RunsTasksOnCurrentThread() const {
46 return queue_
== dispatch_get_current_queue();
49 bool LibDispatchTaskRunner::PostNonNestableDelayedTask(
50 const tracked_objects::Location
& from_here
,
52 base::TimeDelta delay
) {
53 return PostDelayedTask(from_here
, task
, delay
);
56 void LibDispatchTaskRunner::Shutdown() {
57 dispatch_release(queue_
);
59 queue_finalized_
.Wait();
62 dispatch_queue_t
LibDispatchTaskRunner::GetDispatchQueue() const {
66 LibDispatchTaskRunner::~LibDispatchTaskRunner() {
68 dispatch_set_context(queue_
, NULL
);
69 dispatch_set_finalizer_f(queue_
, NULL
);
70 dispatch_release(queue_
);
74 void LibDispatchTaskRunner::Finalizer(void* context
) {
75 LibDispatchTaskRunner
* self
= static_cast<LibDispatchTaskRunner
*>(context
);
76 self
->queue_finalized_
.Signal();