Olive Study Room
[CS] Sync & Async 본문
https://pengcoder.tistory.com/22?category=427332
GCD? (Dispatch Queue & OperationQueue)
앞서 알아야 할 개념 연산 대기열 (Operation Queue) : 비동기적으로 실행되어야 하는 작업을 객체 지향적인 방법으로 사용 종속성 (Depedency) : A작업이 끝나면 B작업을 수행해야하는 관계 [ GCD ] Grand Cen
pengcoder.tistory.com
위 포스팅에 이은 추가 개념!
[ Sync & Async ]
Sync : 순차적 처리(동기적)
Async : 동시적 처리(비동기적)
그렇다면.. Sync와 Serial Queue, Async와 Concurrent Queue는 뭐가 다른가...?!?!?
1. 먼저, Sync와 Serial Queue
Sync는 단일작업의 특성! "내 작업에 대한 답을 받을 때까지 기다린다! 이 작업만 관련있다!"
(큐에서 앞 작업은 sync이고 뒷 작업은 async일 수도 있는 것)
Serial Queue은 내 큐에 들어온 작업들을 순차적으로 실행시킨다!
때문에 Serial Queue에서 sync와 async의 의미는 없다고 볼 수 있다.
예를 들어, 다음과 같은 코드가 있을 때
print("------------")
DispatchQueue.main.async {
for _ in 0...3 {
print("😊")
}
}
for _ in 0...3 {
print("👿")
}
print("===============")
아래와 같은 결과가 나온다.
메인 큐는 serial queue이기 때문에 순차적으로 처리할 수 밖에 없는데,
나머지 print는 sync, 👿는 async이기 때문에 이와 같은 순서로 출력된다.
이미지로 보면 아래와 같다.
(삭제라기 보다는 dequeue. 표현상 편하게 하기 위해...)
2. 다음은 Async와 Concurrent Queue
Async는 단일작업의 특성! "내 작업에 대한 답을 받을 때까지 기다리지 않는다!"
Concurrent Queue는 내 큐에 들어온 작업들을 동시에으로 실행시킨다!
이로써 Sync와 Serial Queue, Async와 Concurrent Queue의 차이는
단일작업의 특성/큐 속 작업을 동시에 또는 순차적으로 처리하는 것
이렇게 종류 자체가 다른 것이라고 이해할 수 있다!
다시 말해서!! Concurrent Queue - Sync인 경우에는 !!!!!!!
let concurrentQueue = DispatchQueue.init(label: "Concurrent Queue", attributes: .concurrent)
concurrentQueue.sync {
for _ in 0..<5 {
print("sync 1")
}
}
concurrentQueue.sync {
for _ in 0..<3 {
print("sync 2")
}
}
sync는 작업이 끝날 때까지 기다리기 때문에(= 동기적) sync 1, sync 2 순으로 실행된다.
...어렵다.
결론은 이렇게 아래 네 가지가 나올 수 있다.
Serial Queue - Sync
Serial Queue - Async
Concurrent Queue - Sync
Concurrent Queue - Async
두 번만 더 해보자!!😣
Concurrent Queue에서의 동기, 비동기 차이를 보면
let concurrentQueue = DispatchQueue.init(label: "Concurrent Queue", attributes: .concurrent)
concurrentQueue.async {
for _ in 0..<5 {
print("async")
}
}
concurrentQueue.sync {
for _ in 0..<5 {
print("sync 1")
}
}
concurrentQueue.sync {
for _ in 0..<5 {
print("sync 2")
}
}
진짜로 마지막!!!!!!!!! 장난질좀 쳐봤다.
let serialQueue = DispatchQueue(label: "Serial Queue")
let concurrentQueue = DispatchQueue.init(label: "Concurrent Queue", attributes: .concurrent)
serialQueue.sync {
for _ in 0..<5 {
print("serialQueue - sync 1")
}
}
concurrentQueue.sync {
for _ in 0..<5 {
print("concurrentQueue - sync 1")
}
}
concurrentQueue.async {
for _ in 0..<5 {
print("concurrentQueue - async")
}
}
serialQueue.async {
for _ in 0..<5 {
print("serialQueue - async")
}
}
concurrentQueue.sync {
for _ in 0..<5 {
print("concurrentQueue - sync 2")
}
}
serialQueue.sync {
for _ in 0..<5 {
print("serialQueue - sync 2")
}
}
ㅋㅋㅋ.. 아무튼 이 코드는
각 큐를 각각 보면 이렇게 실행되는데 이걸 합치면
이렇게 되는 것!!!!!!!!! 진짜 끝!
'Coding' 카테고리의 다른 글
[Design Pattern] 디자인패턴의 정의, GoF, MVC (0) | 2022.01.08 |
---|---|
[GitHub] 내 branch와 master branch의 버전이 일치하지 않는 경우 (0) | 2021.08.24 |
[GitHub 1] 깃허브에 올리기 + Git이란? (0) | 2021.07.05 |
ASCII 아스키코드, UTF-8, Unicode (0) | 2021.06.26 |