Open yyeonjju opened 6 months ago
https://developer.apple.com/videos/play/wwdc2021/10132/?time=1189 More than that, the function may resume onto an entirely different thread. 이 부분은 아직도 이해 못하겠음.
https://tech.devsisters.com/posts/crunchy-concurrency-swift/ 여기서도 나오는 개념
https://developer.apple.com/videos/play/wwdc2021/10132/?time=1189 More than that, the function may resume onto an entirely different thread. 이 부분은 아직도 이해 못하겠음.
https://tech.devsisters.com/posts/crunchy-concurrency-swift/ 여기서도 나오는 개념
이 부분이 저도 헷갈려서 좀 더 찾아봤습니다! concurrency는 GCD와 다르게 비동기 작업이 늘어날 때 스레드를 새로 생성하지 않고 시스템에 제어권을 위임, 시스템이 우선순위에 따라 스레드에게 일을 할당하는 방식입니다. 이 때문에 스레드를 새로 생성하면 해당 스레드가 작업의 완료까지 책임지는 GCD와는 다르게, 2번 스레드에서 suspend 된 작업이 3번 스레드에서 resume 될 수도 있다는 것을 의미하는 것 같아요.
이미 보셨겠지만, 날진님 블로그에 이와 관련한 동작 정리가 잘 나와있더라구요!
https://developer.apple.com/videos/play/wwdc2021/10132/
Swift는 이제 일반적으로 async/await로 알려진 패턴인 비동기 함수를 지원합니다. 함수가 일시 중지되면 어떤 일이 발생하는지 알아보고 기존 완료 핸들러를 비동기 함수에 적용하는 방법을 알아보세요.
썸네일 이미지를 fetching 하는 과정에서 발생하는 비동기 작업
이 작업에 대해 completionHandler를 사용했을 때와 async/await를 사용했을 때를 비교해보자
⭐️ completionHandler 사용했을 때
⭐️ async/await 를 사용했을 때
URLSession의 data(for:) 메서드는 비동기 함수!!
data(for:) 메서드 호출 시 앞에 try가 붙는 이유
data(for:) 메서드는 에러를 던지는 메서드 이기 때문
이전에 “completionHandler 에서 어떻게 에러를 체크하고 명시적으로 completionHandler를 호출했는가”에 대한 모든게 이 “try”에 담겨있다)
data(for:)메서드의 작업(데이터 다운로딩)이 끝났으면, 다시 원래 작업했던 함수로 resume
⭐️ async-await를 사용했을 때 completionHandler로 처리했던 비동기 함수와 다른점!
⭐️ 동기 함수와 비동기 함수의 실행 차이
비동기 함수를 실행했을 때 VS 동기 함수를 실행했을 때의 차이 를 보자면
내부 task 중, 동기 함수가 실행될 경우!!
스레드
는 완료될 때까지 해당 함수를 대신하여 작업을 수행하는 데 완전히 사용됨내부 task 중, 비동기 함수가 실행될 경우는 위와 완전히 다르다!!
suspend→ resume 과정
함수(fetchThumbnail)
가 스레드 제어권 갖고 있다가비동기 함수
에 제어권 넘김시스템
에 제어권 넘긴다.시스템
은 자유롭게 판단할 수 있는데, 일단 시스템이 비동기함수가 가장 중요한 작업이라고 판단하면 비동기 함수를 다시 재개(resume)함 → 이 비동기 함수는 값이나 에러를 리턴함시스템
에 스레드 제어권을 넘기고 "할 일이 많다는 것을 알고 있으니 무엇이 가장 중요한지 결정해라” 라고 하는 것비동기 함수
가 다시 스레드 제어권을 갖게될 것이고, 그럼 해당 비동기 함수 작업을 계속 진행할 수 있다.⭐️
suspending 상태
는 뭘 의미하고,await
키워드가 필요한 이유시스템
에 스레드 제어권을 넘기고 "할 일이 많다는 것을 알고 있으니 무엇이 가장 중요한지 결정해라, 그리고 작업들의 일정을 스케줄링해라” 라고 하는 것==>
즉 함수가 일시중지되면 (중간에 많은 작업이 일어날 수도 있기 때문에) 앱의 상태가 크게 바뀔수도 있다는 점을 인지하고 있어야한다.
await
키워드가 필요한 이유!await
키워드를 통해 나타낼 수 있는데!await
키워드로 표시하도록 주장하는 이유⭐️⭐️async-await 에서 주의해야할 점