LoginSignup
6
6

More than 3 years have passed since last update.

ざっくりと理解するSwift同期処理

Last updated at Posted at 2019-06-30

概要

同期処理を実装する機会があったのでまとめた
syncとasyncの二種類ある
(7/1 syncの部分がasyncになっていたので修正しました)

async: 他のスレッド処理終了を待機しない

async
DispatchQueue.global().async {
  print("global thread start.")
  //何か重い処理
  print("global thread end.")
}
DispatchQueue.global().async {
  print("main thread start.")
  //何か重い処理
  print("main thread end.")
}

# result
global thread start.
main thread start.
global thread end.
main thread end.
async
start==(Thread 1)==>end  
start==(Thread 2)=====>end

いわゆる並列処理
重い処理の裏で別処理を動かしたいときなどに使える

sync: 他のスレッド処理終了を待機する

sync
DispatchQueue.global().async {
  print("global thread start.")
  //何か重い処理
  print("global thread end.")
}
DispatchQueue.global().sync {
  print("main thread start.")
  //何か重い処理
  print("main thread end.")
}

# result
global thread start.
global thread end.
main thread start.
main thread end.
sync
start==(Thread 1)==>end  start==(Thread 2)====>end

いわゆる直列処理
クリティカルセクションなどに使える

6
6
2

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
6
6