LoginSignup
3
3

More than 5 years have passed since last update.

Dispatchクラスのメモ

Posted at

Getting started with GCD in MacRuby & Rubymotion - Mateus - Weltを読んだ際のメモ。

アプリケーションのメインのキューを取得

Dispatch::Queue.main

並列処理用のキューを取得

Dispatch::Queue.concurrent
Dispatch::Queue.concurrent('hoge')

優先度を指定することも可能。

Dispatch::Queue.concurrent(priority=:default)
Dispatch::Queue.concurrent(priority=:low)
Dispatch::Queue.concurrent(priority=:high)

カスタマイズされたキューを取得

自身で実行順序などが予想できる場合に使う?

Dispatch::Queue.new('hoge')

同期で処理を実行

Dispatch::Queue.concurrent.sync {p 'hoge'}

非同期で処理を実行

Dispatch::Queue.concurrent.async {p 'hoge'}

指定時間後に処理を実行

# .0を付けなくても動いた
# 単位は秒
Dispatch::Queue.concurrent.after(5.0) {p 'hoge'}

指定回数分処理を実行

Dispatch::Queue.concurrent.apply(5) {|i| p i}

キューを操作する

q = Dispatch::Queue.concurrent('hoge')
# 一時停止
q.suspend!
p q.suspended?
# => true
# 再開
q.resume!
p q.suspended?
# => false

複数のキューの終了を待つ

キューを管理するDipatch::Groupなるクラスの配下にDispatch::Queueを所属させる感じ。

group = Dispatch::Group.new
hoge = Dispatch::Queue.concurrent
fuga = Dispatch::Queue.concurrent

hoge.async(group) { p 'hoge'}
fuga.async(group) { p 'fuga'}

group.wait

キューの終了時に処理を実行する

group = Dispatch::Group.new
hoge = Dispatch::Queue.concurrent

hoge.async(group) { p 'hoge'}
group.notify(hoge) {p 'hoge complete'}

waitnotifyを同時に使った場合、wait以降の処理の後、notifyで指定した処理が実行されてるっぽいけど詳細は不明。

Barriers

Dancing with GCD Group and Barriers - Mateus - Welt にある下記のサンプルを動かしてみたけど自身の環境ではコメントにあるような動作にならず結果は""だった。

queue = Dispatch::Queue.concurrent('com.company.application.task')
@i = ""
queue.async { @i += 'a' }
queue.async { @i += 'b' }
queue.barrier_async { @i += 'c' }
p @i #=> either prints out 'abc' or 'bac'
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3