LoginSignup
5
5

More than 5 years have passed since last update.

マルチスレッド手法GCD(Grand Central Dispatch)

Last updated at Posted at 2015-08-29

マルチスレッドによる並列処理についてしらべました。

通信処理などを行う際などにアプリで平行して別の処理をしたい場合にマルチスレッド化が必要になってきます。メインスレッドですべての処理をおこなうと一つずつ実行していくため、ある処理に時間がかかると他のアクションへの反応ができずに固まった状態に陥ってしまいます。

同時に並列して処理を行うためには別スレッドを用意し、それに処理を追加して順番に実行していくという方法をとります。

タスクを非同期に実行する技術のひとつとして、Grand CentralDispatch(GCD)が用いられます。
dispatch queueといい、タスクを追加していくと順番に処理を行っていきます。

主に2つの関数があります。
・dispatch_async・・・非同期実行
・dispatch_sync・・・同期実行

func performSlowCalculationAsynchronously(someString: String, anotherInt: Int, completionHandler: (result: Int) -> ()) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
        let result = self.performSlowCalculation(someString, anotherInt: anotherInt)

        completionHandler(result: result)
    }
}
5
5
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
5
5