Class: Dispatch::Queue
Overview
A Dispatch::Queue is the fundamental mechanism for scheduling blocks for execution, either synchronously or asychronously.
All blocks submitted to dispatch queues begin executing in the order they were received. The system-defined concurrent queues can execute multiple blocks in parallel, depending on the number of idle threads in the thread pool. Serial queues (the main and user-created queues) wait for the prior block to complete before dequeuing and executing the next block.
Queues are not bound to any specific thread of execution and blocks submitted to independent queues may execute concurrently.
Class Method Summary (collapse)
- + alloc
-
+ Dispatch::Queue.concurrent
Returns one of the global concurrent priority queues.
-
+ Dispatch::Queue.current
When called from within a block that is being dispatched on a queue, this returns the queue in question.
-
+ Dispatch::Queue.main
Returns the dispatch queue for the main thread.
Instance Method Summary (collapse)
-
- after { ... }
Runs the passed block after the given delay (in seconds) using dispatch_after(3),.
-
- apply {|index| ... }
Runs a block count number of times asynchronously via dispatch_apply(3), passing in an index and waiting until all of them are done.
-
- async { ... }
Yields the passed block asynchronously via dispatch_async(3):.
-
- barrier_async { ... }
This function is a specialized version of the #async dispatch function.
-
- barrier_async { ... }
This function is identical to the #barrier_async function; however, it blocks until the provided block is executed.
-
- Dispatch::Queue.new
constructor
Returns a new serial dispatch queue.
-
- to_s
Returns the label of the dispatch queue.
-
- sync { ... }
Yields the passed block synchronously via dispatch_sync(3):.
-
- to_s
Returns the label of the dispatch queue.
Methods inherited from Object
#dispatch_object, #resume!, #suspend!, #suspended?
Methods inherited from NSObject
#!, #!=, #!~, #<=>, #==, #===, #=~, #Rational, #__callee__, #__method__, #__send__, #__type__, `, allocWithZone:, #autoContentAccessingProxy, autoload, autoload?, autorelease_pool, #awakeAfterUsingCoder:, binding, block_given?, caller, cancelPreviousPerformRequestsWithTarget:, cancelPreviousPerformRequestsWithTarget:selector:object:, catch, class, classFallbacksForKeyedArchiver, #classForCoder, #classForKeyedArchiver, classForKeyedUnarchiver, #clone, conformsToProtocol:, #copy, copyWithZone:, #dealloc, #define_singleton_method, description, display, #doesNotRecognizeSelector:, #dup, #enum_for, #eql?, #equal?, #extend, fail, #finalize, format, #forwardInvocation:, #forwardingTargetForSelector:, framework, #freeze, #frozen?, getpass, gets, global_variables, #init, initialize, #initialize_clone, #initialize_copy, #initialize_dup, #inspect, instanceMethodForSelector:, instanceMethodSignatureForSelector:, #instance_eval, #instance_exec, #instance_of?, #instance_variable_defined?, #instance_variable_get, #instance_variable_set, #instance_variables, instancesRespondToSelector:, isSubclassOfClass:, #is_a?, iterator?, #kind_of?, lambda, load, load_bridge_support_file, load_plist, local_variables, loop, #method, #methodForSelector:, #methodSignatureForSelector:, #methods, #mutableCopy, mutableCopyWithZone:, new, #nil?, open, p, #performSelector:onThread:withObject:waitUntilDone:, #performSelector:onThread:withObject:waitUntilDone:modes:, #performSelector:withObject:afterDelay:, #performSelector:withObject:afterDelay:inModes:, #performSelectorInBackground:withObject:, #performSelectorOnMainThread:withObject:waitUntilDone:, #performSelectorOnMainThread:withObject:waitUntilDone:modes:, print, printf, #private_methods, proc, #protected_methods, #public_method, #public_methods, #public_send, putc, puts, raise, rand, readline, readlines, #replacementObjectForCoder:, #replacementObjectForKeyedArchiver:, require, resolveClassMethod:, resolveInstanceMethod:, #respond_to?, #respond_to_missing?, select, #send, setVersion:, #singleton_methods, sprintf, srand, superclass, #taint, #tainted?, #tap, test, throw, #to_plist, trace_var, trap, #trust, #untaint, untrace_var, #untrust, #untrusted?, version
Constructor Details
- (Dispatch::Queue) Dispatch(label)
Returns a new serial dispatch queue.
A dispatch is a FIFO queue to which you can submit tasks via a block. Blocks submitted to dispatch queues are executed on a pool of threads fully managed by the system. Dispatched tasks execute one at a time in FIFO order. GCD takes take of using multiple cores effectively to better accommodate the needs of all running applications, matching them to the available system resources in a balanced fashion.
Use serial GCD queues to ensure that tasks execute in a predictable order. It's a good practice to identify a specific purpose for each serial queue, such as protecting a resource or synchronizing key processes. Create as many as you need - serial queues are extremely lightweight (with a total memory footprint of less than 300 bytes); however, remember to use concurrent queues if you need to perform idempotent tasks in parallel. Dispatch queues need to be labeled and thereofore you need to pass a name to create your queue. By convention, labels are in reverse-DNS style.
gcdq = Dispatch::Queue.new('org.macruby.gcd.example')
gcdq.async { p 'doc' }
gcdq.async { p 'bar' }
gcdq.sync {}
Dynamic Method Handling
This class handles dynamic methods through the method_missing method in the class NSObject
Class Method Details
+ (Object) alloc
+ (Dispatch::Queue) Dispatch(priority = :default)
Returns one of the global concurrent priority queues.
A dispatch queue is a FIFO queue that accepts tasks in the form of a block. Blocks submitted to dispatch queues are executed on a pool of threads fully managed by the system. Dispatched tasks execute one at a time in FIFO order. GCD takes take of using multiple cores effectively and better accommodate the needs of all running applications, matching them to the available system resources in a balanced fashion.
Use concurrent queues to execute large numbers of tasks concurrently. GCD automatically creates three concurrent dispatch queues that are global to your application and are differentiated only by their priority level.
The three priority levels are: :low, :default, :high, corresponding to the DISPATCH_QUEUE_PRIORITY_HIGH, DISPATCH_QUEUE_PRIORITY_DEFAULT, and DISPATCH_QUEUE_PRIORITY_LOW (detailed in the dispatch_queue_create(3) man page). The GCD thread dispatcher will perform actions submitted to the high priority queue before any actions submitted to the default or low queues, and will only perform actions on the low queues if there are no actions queued on the high or default queues. When installed on Mac OS 10.7 or later, the :background priority level is available. Actions submitted to this queue will execute on a thread set to background state (via setpriority(2)), which throttles disk I/O and sets the thread's scheduling priority to the lowest value possible.
On Mac OS 10.7 and later, passing a string to concurrent creates a new concurrent queue with the specified string as its label. Private concurrent queues created this way are identical to private FIFO queues created with new, except for the fact that they execute their blocks in parallel.
gcdq = Dispatch::Queue.concurrent(:high)
5.times { gcdq.async { print 'foo' } }
gcdq_2 = Dispatch::Queue.concurrent(:low)
gcdq_2.sync { print 'bar' } # will always print 'foofoofoofoofoobar'.
+ (Dispatch::Queue) Dispatch
When called from within a block that is being dispatched on a queue, this returns the queue in question. If executed outside of a block, the result depends on whether the run method has been called on the main queue: if it has, it returns the main queue, otherwise it returns the default-priority concurrent queue.
+ (Dispatch::Queue) Dispatch
Returns the dispatch queue for the main thread.
Instance Method Details
- (Object) after(delay) { ... }
Runs the passed block after the given delay (in seconds) using dispatch_after(3),
gcdq.after(0.5) { puts 'wait is over :)' }
- (Object) apply(count) {|index| ... }
Runs a block count number of times asynchronously via dispatch_apply(3), passing in an index and waiting until all of them are done. You must use a concurrent queue to run the blocks concurrently.
gcdq = Dispatch::Queue.new('doc')
@result = Array.new(5)
gcdq.apply(5) {|i| @result[i] = i*i }
p @result #=> [0, 1, 4, 9, 16]
- (Object) async(group = nil) { ... }
Yields the passed block asynchronously via dispatch_async(3):
gcdq = Dispatch::Queue.new('doc')
@i = 0
gcdq.async { @i = 42 }
while @i == 0 do; end
p @i #=> 42
If a group is specified, the dispatch will be associated with that group via dispatch_group_async(3):
gcdq = Dispatch::Queue.new('doc')
gcdg = Dispatch::Group.new
@i = 3.1415
gcdq.async(gcdg) { @i = 42 }
gcdg.wait
p @i #=> 42
- (Object) barrier_async { ... }
This function is a specialized version of the #async dispatch function. When a block enqueued with barrier_async reaches the front of a private concurrent queue, it waits until all other enqueued blocks to finish executing, at which point the block is executed. No blocks submitted after a call to barrier_async will be executed until the enqueued block finishes. It returns immediately.
If the provided queue is not a concurrent private queue, this function behaves identically to the #async function.
This function is only available on OS X 10.7, iOS 4.3 (and later).
gcdq = Dispatch::Queue.concurrent('org.macruby.documentation')
@i = ""
gcdq.async { @i += 'a' }
gcdq.async { @i += 'b' }
gcdq. { @i += 'c' }
p @i #=> either prints out 'abc' or 'bac'
- (Object) barrier_async { ... }
This function is identical to the #barrier_async function; however, it blocks until the provided block is executed.
If the provided queue is not a concurrent private queue, this function behaves identically to the #sync function.
This function is only available on OS X 10.7, iOS 4.3 (and later).
gcdq = Dispatch::Queue.concurrent('org.macruby.documentation')
@i = ""
gcdq.async { @i += 'a' }
gcdq.async { @i += 'b' }
gcdq. { @i += 'c' } # blocks
p @i #=> either prints out 'abc' or 'bac'
- (String) to_s
Returns the label of the dispatch queue
gcdq = Dispatch::Queue.new('doc')
gcdq.to_s #=> 'doc'
gcdq = Dispatch::Queue.main
gcdq.to_s #=> 'com.apple.main-thread'
- (Object) sync { ... }
Yields the passed block synchronously via dispatch_sync(3):
gcdq = Dispatch::Queue.new('doc')
@i = 42
gcdq.sync { @i = 42 }
p @i #=> 42
- (String) to_s
Returns the label of the dispatch queue
gcdq = Dispatch::Queue.new('doc')
gcdq.to_s #=> 'doc'
gcdq = Dispatch::Queue.main
gcdq.to_s #=> 'com.apple.main-thread'