<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Noah on Medium]]></title>
        <description><![CDATA[Stories by Noah on Medium]]></description>
        <link>https://medium.com/@dev.noah0316?source=rss-bb5cbd32d89------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ryxWp9l6cZEe64fPRgMmeA.png</url>
            <title>Stories by Noah on Medium</title>
            <link>https://medium.com/@dev.noah0316?source=rss-bb5cbd32d89------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 10:05:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dev.noah0316/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[확신이 없다면 Checked Continuation을!]]></title>
            <link>https://medium.com/daily-monster/%ED%99%95%EC%8B%A0%EC%9D%B4-%EC%97%86%EB%8B%A4%EB%A9%B4-checked-continuation%EC%9D%84-6034a944fafa?source=rss-bb5cbd32d89------2</link>
            <guid isPermaLink="false">https://medium.com/p/6034a944fafa</guid>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Noah]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 07:18:37 GMT</pubDate>
            <atom:updated>2024-03-21T08:12:34.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7uHGkbjHqi4BSgbO" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>안녕하세요! 목요괴물 Noah입니다!</p><p>URL의 미리보기 이미지(대표 이미지)를 Apple의 <a href="https://developer.apple.com/documentation/linkpresentation?ref=noah-ios.dev">Link Presentation</a> 프레임워크를 이용해 불러오도록 개발하다, 특정 링크의 경우 아래와 같이 continuation misuse로 인한 leak이 발생하는 것을 확인하여 주의할 점에 대해 기록 삼아 남겨보도록 하겠습니다!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*RtY6mTVO6QRyDYBg_nRTPQ.gif" /></figure><p>무엇이 문제였는지, 작성한 코드를 확인해 보도록 하겠습니다.</p><h3>Before</h3><pre>func requestPreviewImage() async throws -&gt; UIImage {<br>  let primaryImageProvider = self.linkMetadata?.imageProvider ?? self.linkMetadata?.iconProvider<br>  return try await withCheckedThrowingContinuation { continuation in<br>    primaryImageProvider?.loadObject(ofClass: UIImage.self) { (previewImage, error) in<br>      guard let previewImage = previewImage as? UIImage,<br>      error == nil<br>      else {<br>        continuation.resume(throwing: LinkMetadataServiceError.contentsCouldNotBeLoaded)<br>        return<br>      }<br>  <br>      continuation.resume(returning: previewImage)<br>    }<br>  }<br>}</pre><p>기존 completion Handler 기반의 코드를 Swift Concurrency로 bridge 해주기 위해 CheckedContinuation을 사용해 주었습니다.</p><p>CheckedContinuation을 사용해 주었기에 디버깅 콘솔에서 아래와 같은 메시지를 확인할 수 있습니다.</p><pre>SWIFT TASK CONTINUATION MISUSE: requestPreviewImage() leaked its continuation!</pre><h3>어디가 문제였을까?</h3><p>imageProvider, iconProvider에 모두 nil이 할당되어 primaryImageProvider 에 nil이 들어가게 된다면?</p><pre>func requestPreviewImage() async throws -&gt; UIImage {<br>  let primaryImageProvider = self.linkMetadata?.imageProvider ?? self.linkMetadata?.iconProvider<br>  return try await withCheckedThrowingContinuation { continuation in<br>    primaryImageProvider?.loadObject(ofClass: UIImage.self) { (previewImage, error) in<br>      guard let previewImage = previewImage as? UIImage,<br>      error == nil<br>      else {<br>        continuation.resume(throwing: LinkMetadataServiceError.contentsCouldNotBeLoaded)<br>        return<br>      }<br>		<br>      continuation.resume(returning: previewImage)<br>    }<br><br>    // nil일 경우 오게되는 컨텍스트<br>  }<br>}</pre><p><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/optionalchaining/?ref=noah-ios.dev#Calling-Methods-Through-Optional-Chaining">Optional Chaining</a>을 이용해 메소드를 호출했기 때문에 nil로 평가되어 loadObject메소드를 호출하지 못하고 다음 컨텍스트로 넘어가게 됩니다.</p><p>따라서 continuation의 인터페이스를 호출하지 못하게 되어 continuation misuse로 인한 leak이 발생하게 됩니다.</p><p>문제를 알게 되었으니, 코드를 수정해 보도록 하겠습니다.</p><h3>After</h3><pre>func requestPreviewImage() async throws -&gt; UIImage {<br>  guard let linkMetadata = self.linkMetadata,<br>        let primaryImageProvider = linkMetadata.imageProvider ?? linkMetadata.iconProvider,<br>        primaryImageProvider.canLoadObject(ofClass: UIImage.self)<br>  else { throw LinkMetadataServiceError.contentsCouldNotBeLoaded }<br>		<br>  return try await withCheckedThrowingContinuation { continuation in<br>    primaryImageProvider.loadObject(ofClass: UIImage.self) { (previewImage, error) in<br>      guard let previewImage = previewImage as? UIImage,<br>      error == nil<br>      else {<br>        continuation.resume(throwing: LinkMetadataServiceError.contentsCouldNotBeLoaded)<br>        return<br>      }<br>  <br>      continuation.resume(returning: previewImage)<br>    }<br>  }<br>}</pre><p>guard 구문에서 Optional Binding을 해주고, NSItemProvider의 <a href="https://developer.apple.com/documentation/foundation/nsitemprovider/2888333-canloadobject?ref=noah-ios.dev">canLoadObject(ofClass:)</a><br>를 이용해 객체를 로드할 수 있는지 확인한 뒤에 조건문을 통과하지 못한다면 에러를 throw하며 early exit하도록 해주어 문제를 해결할 수 있었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*efs4xLuWZFp5qKNBbIxSDQ.gif" /></figure><h3>Conclusion</h3><p>continuation을 사용할 때는 코드 실행 경로에서 resume은 코드 실행 경로에서 딱 한 번 호출되어야 한다는 것에 유의해서 코드를 작성하다 보니 두 번 이상 호출하지 않도록 하는 부분은 신경을 썼었는데,</p><p>이번 경우처럼 한 번도 호출하지 못하는 경우에 대해서는 신경을 쓰지 못했던 것 같습니다.</p><p>그래도 다행인 부분은 <a href="https://developer.apple.com/documentation/swift/withcheckedthrowingcontinuation(function:_:)?ref=noah-ios.dev">withCheckedThrowingContinuation(function:_:)</a>을 사용했기에 빠르게 문제를 확인할 수 있었습니다.</p><p>checkedContinuation은 런타임에 misuse에 대한 검사를 하기 때문에 unsafeContinuation보다 오버헤드가 있긴 하지만, 이처럼 개발을 하는 과정 중에 빠르게 문제를 확인할 수 있게 도와주어 misuse에 대한 확신이 없는 경우에 좋은 것 같습니다.</p><p>읽어주셔서 감사합니다 :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6034a944fafa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daily-monster/%ED%99%95%EC%8B%A0%EC%9D%B4-%EC%97%86%EB%8B%A4%EB%A9%B4-checked-continuation%EC%9D%84-6034a944fafa">확신이 없다면 Checked Continuation을!</a> was originally published in <a href="https://medium.com/daily-monster">daily-monster</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Concurrency 이전의 동시성 프로그래밍]]></title>
            <link>https://medium.com/daily-monster/swift-concurrency-%EC%9D%B4%EC%A0%84%EC%9D%98-%EB%8F%99%EC%8B%9C%EC%84%B1-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D-50a224d14dc8?source=rss-bb5cbd32d89------2</link>
            <guid isPermaLink="false">https://medium.com/p/50a224d14dc8</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <dc:creator><![CDATA[Noah]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 02:47:11 GMT</pubDate>
            <atom:updated>2024-03-14T02:49:24.359Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HHRUTO3qOlpDyIU2" /><figcaption>Photo by <a href="https://unsplash.com/@denleyphotography?utm_source=medium&amp;utm_medium=referral">Denley Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>들어가며</h3><p>안녕하세요! 목요괴물 Noah입니다!</p><p>오늘은 Swift Concurrency가 도입되기 이전에 동시성 프로그래밍을 수행하는 데 사용된 도구에 대해 알아보려 합니다.</p><p>또한 Swift Concurrency 이전에는 동시성 프로그래밍을 구현하기 위해 어떠한 도구들을 사용했는지, 어떠한 맥락으로 동시성 프로그래밍을 도와주는 도구들이 등장하게 되었는지 살펴보도록 하겠습니다.</p><h3>Thread</h3><p>동시성 프로그래밍을 할 때 ‘스레드’라는 단어가 많이 언급되는데요, 스레드를 많이 쓰면 쓸수록 더 많은 작업을 동시적으로 실행할 수 있으니, 스레드는 많을수록 좋은 걸까요?</p><blockquote>“동시”라는 단어에 대한 맥락은 <a href="https://medium.com/daily-monster/%EB%8F%99%EC%8B%9C%EC%84%B1%EA%B3%BC-%EB%B3%91%EB%A0%AC%EC%84%B1%EC%9D%98-%EC%B0%A8%EC%9D%B4-19b5843e34e7">이전 포스트</a>와 같이합니다!</blockquote><p>아래의 표를 볼까요?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vN_ujRwTLxuet3Zi" /><figcaption>출처 : <a href="https://www.baeldung.com/cs/servers-threads-number?ref=noah-ios.dev">https://www.baeldung.com/cs/servers-threads-number</a></figcaption></figure><p>스레드의 수가 많아짐에 따라 퍼포먼스(시간 당 작업효율)가 올라가지만, 어느 순간부터는 더 이상 퍼포먼스가 향상되지 않는 구간이 나타나는데요,</p><p>이는 CPU의 스레드가 많아질수록 스레드 스위칭 등의 오버헤드가 발생하게 되어 코어당 일정 수의 스레드가 넘어가게 될 경우 성능에 좋지 않은 영향을 미치게 되기 때문입니다.</p><blockquote>이를 thread-explosion이라고 합니다.</blockquote><p>따라서 대부분의 CPU 제조사는 스레드가 아닌, 코어 수를 증가시켜 병렬처리로 인한 성능 향상을 꾀하는 식으로 CPU를 발전시켜 나가고 있습니다.</p><p>늘어난 코어만큼 사용자가 컴퓨터가 빨라졌다는걸 느끼게 하려면 스레드는 CPU 코어 수에 맞추어 적당하게 만들고, 만들어놓은 스레드를 활용하기 위해 스레드에서 돌아가는 코드들을 빠르게 다른 코드로 교체해 줘야 효율적으로 돌아가는 것으로 느끼게 될 것입니다.</p><p>프로세스 내의 user-level 스레드 역시 동일한 논리를 따릅니다.</p><blockquote>방금 언급한 스레드는 CPU 코어에서 동작하는 CPU 스레드를 말합니다.<br>밑에서 살펴보겠지만 우리가 이번 글에서 다루게 될 스레드는 user-level 스레드, 프로세스 내에서 실행되는 세부 작업의 단위입니다.<br>따라서 아래의 글에서 등장하는 스레드는 특별한 언급이 없는 이상 user-level 스레드를 말합니다 :)</blockquote><p>따라서 프로그래밍 방식도 역시 과도하게 스레드를 많이 만들어 스레드 스위치와 같은 오버헤드를 비용을 발생시키는 것보다 시스템이 만들어 놓은 스레드에 실행할 코드를 보내는 식으로 발전하게 됩니다.</p><p>애플 개발 생태계에서도 역시 스레드를 생성해 사용하는 API가 있지만, 프로그래밍 방식이 변화함에 따라 이제는 잘 사용하지 않고 있습니다.</p><p>스레드, 한번 만들어볼까요?</p><h3>NSThread</h3><p>URL로부터 데이터를 가져온 후, 콘솔에 출력하는 함수를 동기적으로 구성한 다음, 스레드를생성한 후에 해당 함수를 생성한 user-level 스레드에서 실행하는 간단한 예제를 만들어봅시다.</p><p>먼저 URL로부터 데이터를 가져온 후, 콘솔에 출력하는 함수를 아래와 같이 동기적으로 구성해 봅시다.</p><pre>func fetchAndPrintHTML(from url: URL) {<br>  let responseData = try! Data(contentsOf: url)<br>  print(String(data: responseData, encoding: .utf8)!)<br>}</pre><p>위 함수의 첫 번째 줄을 살펴보면 파라미터로 받은 url을 이용해 <a href="https://developer.apple.com/documentation/foundation/nsdata/1413892-init?ref=noah-ios.dev">Data</a> 생성자를 이용해 동기적으로 데이터를 가져오기 때문에 네트워크 요청이 완료될 때까지 해당 함수를 실행하는 스레드가 차단될 것입니다.</p><p>그다음으로 해당 함수를 실행할 스레드를 생성해 보도록 하겠습니다.</p><pre>final class NetworkRequestManager {<br>  private var networkRequestThread: Thread? = nil<br><br>  func startRequest() {<br>    self.networkRequestThread = Thread(<br>      target: self,<br>      selector: #selector(self.fetchAndPrintHTML(from:)),<br>      object: URL(string: &quot;https://www.naver.com&quot;)!<br>    )<br>    self.networkRequestThread?.start()<br>  }<br>}</pre><p>startRequest 함수에서는 NSThread(일명 Cocoa thread)를 이용해 스레드를 생성해 주고 있는데요, NSThread는 이미 실행 중인 스레드에서 새 스레드를 생성하고, 코드를 실행하는 데 사용할 수 있는 메서드를 제공합니다.</p><p>NSThread를 이용해 스레드를 생성하는 방법은 크게 두 가지가 있습니다.</p><ol><li>새 NSThread 객체를 만들고 start 메서드를 명시적으로 호출하는 방법과</li><li>detachNewThreadSelector:toTarget:withObject: 클래스 메서드를 사용하여 새 스레드를 생성하는 방법이 있습니다.</li></ol><blockquote>공식 문서 참조: <a href="https://developer.apple.com/documentation/foundation/thread?ref=noah-ios.dev">https://developer.apple.com/documentation/foundation/thread</a></blockquote><p>이 방법 중 첫 번째 방법을 사용해 NSThread 객체를 생성해 주었는데요,</p><pre>self.networkRequestThread = Thread(<br>  target: self,<br>  selector: #selector(self.fetchAndPrintHTML(from:)),<br>  object: URL(string: &quot;https://www.naver.com&quot;)!<br>)</pre><p>스레드가 실행할 메서드가 속한 객체와, 실행할 메서드, 메서드를 호출할 때 필요한 객체를 지정해 주었습니다.</p><p>그다음</p><pre>self.networkRequestThread?.start()</pre><p>스레드의 start 메서드를 이용해 스레드를 시작해 주었습니다.</p><p>네트워크 요청을 하는 함수를 동기적으로 구성한 후, 해당 함수를 NSThread 생성자를 이용해 생성한 스레드에서 실행할 수 있게 되었는데요, 이제 작성한 코드를 다시 구성해 보도록 하겠습니다.</p><pre>final class NetworkRequestManager {<br>  private var networkRequestThread: Thread? = nil<br>	<br>  func startRequest() {<br>    self.networkRequestThread = Thread(<br>      target: self,<br>      selector: #selector(self.fetchAndPrintHTML(from:)),<br>      object: URL(string: &quot;https://www.naver.com&quot;)!<br>    )<br>    self.networkRequestThread?.start()<br>  }<br><br>  @objc private func fetchAndPrintHTML(from url: URL) {<br>    let responseData = try! Data(contentsOf: url)<br>    print(String(data: responseData, encoding: .utf8)!)<br>  }<br>	<br>  deinit {<br>    self.networkRequestThread?.cancel()<br>    self.networkRequestThread = nil<br>  }<br>}</pre><blockquote>#selector 에 사용되는 함수는 Objective-C에서 호출될 수 있도록 @objc 키워드가 붙어있어야 하므로 위에서 작성한 함수에 @objc 키워드를 붙여주었습니다.</blockquote><p>작성한 코드를 실행해 볼까요?</p><pre>let networkRequestManager = NetworkRequestManager()<br>networkRequestManager.startRequest()<br>print(&quot;안녕하세요&quot;)<br><br>RunLoop.main.run()</pre><p>만약 startRequest함수가 스레드를 생성하지 않고 네트워크 요청을 동기적으로 처리했다면, startRequest함수 내부의 네트워크 요청이 완료된 후에 &quot;안녕하세요&quot;라는 문자열이 출력되었을 것입니다.</p><p>하지만, 우리는 스레드를 생성한 후에 동기적으로 구성한 네트워크 요청을 해당 스레드에서 실행하도록 코드를 작성했으며, 네트워크 요청보다 콘솔에 출력하는 작업은 상대적으로 빠르게 실행되기 때문에 콘솔에서 아래와 같은 결과를 확인할 수 있습니다.</p><pre>안녕하세요<br>   &lt;!doctype html&gt; &lt;html lang=&quot;ko&quot; class=&quot;fzoom&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta name=&quot;Referrer&quot; content=&quot;origin&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=1190&quot;&gt; &lt;title&gt;NAVER&lt;/title&gt; &lt;meta name=&quot;apple-mobile-web-app-title&quot; content=&quot;NAVER&quot;/&gt; &lt;meta name=&quot;robots&quot; content=&quot;index,nofollow&quot;/&gt; &lt;meta name=&quot;description&quot; content=&quot;네이버 메인에서 다양한 정보와 유용한 컨텐츠를 만나 보세요&quot;/&gt; &lt;meta property=&quot;og:title&quot; content=&quot;네이버&quot;&gt; &lt;meta property=&quot;og:url&quot; content=&quot;https://www.naver.com/&quot;&gt; &lt;meta property=&quot;og:image&quot; content=&quot;https://s.pstatic.net/static/www/mobile/edit/2016/0705/mobile_212852414260.png&quot;&gt; &lt;meta property=&quot;og:description&quot; content=&quot;네이버 메인에서 다양한 정보와 유용한 컨텐츠를 만나 보세요&quot;/&gt; &lt;meta name=&quot;twitter:card&quot; content=&quot;summary&quot;&gt; <br>/ ... /</pre><p>Swift에서 스레드를 만들어 사용하기 위해서는 위와 같은 방법을 사용하거나 조금 더 복잡하고, 세부적인 작업이 필요하다면 NSThread를 상속한 후에 코드를 작성할 수 있습니다.</p><p>방금 우리가 살펴본 방식은 개발자가 스레드를 생성하고, 어떤 스레드가 있는지 확인한 후에 특정 스레드가 해당 메서드를 실행할 수 있도록 개발자가 결정하는 방식입니다.</p><p>앞서</p><blockquote>“프로그래밍 방식도 과도하게 스레드를 많이 만들어 스레드 스위치와 같은 오버헤드를 비용을 발생시키는 것보다 시스템이 만들어 놓은 스레드에 실행할 코드를 보내는 식으로 발전하게 됩니다.”</blockquote><p>라는 말을 했었는데요, 우리가 방금 살펴본 방식은 개발자가 스레드를 생성하고, 스레드를 실행하는 메커니즘이기 때문에 과도하게 스레드가 많이 생성될 수 있는 문제와 여러 휴먼 에러의 발생위험이 있습니다.</p><p>또한 이를 올바르게 작성했는지 검증하기 위한 디버깅, 테스팅 비용을 지불해야할 것입니다.</p><p>따라서 뒤에 등장하게 될 동시성 프로그래밍을 도와주는 도구들은 CPU 코어 개수에 맞게 스레드를 시스템이 생성하고, 시스템이 만들어놓은 스레드에 개발자가 작성한 코드를 전달하는 방식을 도입하게 됩니다.</p><p>결국 개발자가 작성한 코드의 단위는 클로져가 되고, 해당 클로져를 시스템이 관리하는 큐에 제출하고, 큐에 있는 클로져를 가용한 스레드에 시스템이 분배하는 방식이 <a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html?ref=noah-ios.dev#//apple_ref/doc/uid/TP40008091-CH102-SW1">Grand Central Dispatch(GCD)</a>입니다.</p><h3>Grand Central Dispatch</h3><p>GCD를 이용해, 앞서 보았던 예제인 네트워크 요청을 동기적으로 구성한 다음, 해당 코드를 다른 스레드에서 실행할 수 있도록 하는 예제를 최대한 비슷하게 다시 만들어봅시다.</p><p>먼저 시스템이 관리할 큐를 생성해 보도록 합시다.</p><pre>final class NetworkRequestManager {<br>  private let networkRequestQueue = DispatchQueue(<br>    label: &quot;com.example.networkRequestQueue&quot;<br>  )<br>}</pre><p>DispatchQueue(label:) 생성자를 이용해 private concurrent queue를 생성해 주었습니다.</p><p>다음으로 클로저 단위의 작업을 캡슐화하는 DispatchWorkItem을 선언해 주도록 하겠습니다.</p><pre>final class NetworkRequestManager {<br>  private let networkRequestQueue = DispatchQueue(<br>    label: &quot;com.example.networkRequestQueue&quot;<br>  )<br>  private var fetchHTMLWorkItem: DispatchWorkItem? = nil<br>}</pre><p>앞에서 살펴본 예제와 같이 네트워크 요청을 동기적으로 한 후에 응답을 콘솔에 출력하는 함수를 추가하도록 하겠습니다.</p><pre>final class NetworkRequestManager {<br>  private let networkRequestQueue = DispatchQueue(<br>    label: &quot;com.example.networkRequestQueue&quot;<br>  )<br>  private var fetchHTMLWorkItem: DispatchWorkItem?<br><br>  private func fetchAndPrintHTML(from url: URL) {<br>    let responseData = try! Data(contentsOf: url)<br>    print(String(data: responseData, encoding: .utf8)!)<br>  }<br>}</pre><p>이제 해당 함수를 실행하기 위해 큐에 작업을 제출하는 코드를 추가해 보겠습니다.</p><pre>final class NetworkRequestManager {<br>  private let networkRequestQueue = DispatchQueue(<br>    label: &quot;com.example.networkRequestQueue&quot;<br>  )<br>  private var fetchHTMLWorkItem: DispatchWorkItem?<br><br>  private func fetchAndPrintHTML(from url: URL) {<br>    let responseData = try! Data(contentsOf: url)<br>    print(String(data: responseData, encoding: .utf8)!)<br>  }<br>	<br>  func startRequest() {<br>    self.fetchHTMLWorkItem = DispatchWorkItem {<br>      self.fetchAndPrintHTML(from: URL(string: &quot;https://www.naver.com&quot;)!)<br>    }<br>    <br>    if let workItem = self.fetchHTMLWorkItem {<br>      self.networkRequestQueue.async(execute: workItem)<br>    }<br>  }<br><br>  deinit {<br>    self.fetchHTMLWorkItem?.cancel()<br>  }<br>}</pre><p>작성한 코드 예제를 실행해 보도록 하겠습니다.</p><pre>let networkRequestManager = NetworkRequestManager()<br>networkRequestManager.startRequest()<br><br>print(&quot;안녕하세요&quot;)<br><br>RunLoop.main.run()</pre><p>결과를 확인해 봅시다.</p><pre>안녕하세요<br>   &lt;!doctype html&gt; &lt;html lang=&quot;ko&quot; class=&quot;fzoom&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta name=&quot;Referrer&quot; content=&quot;origin&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=1190&quot;&gt; &lt;title&gt;NAVER&lt;/title&gt; &lt;meta name=&quot;apple-mobile-web-app-title&quot; content=&quot;NAVER&quot;/&gt; &lt;meta name=&quot;robots&quot; content=&quot;index,nofollow&quot;/&gt; &lt;meta name=&quot;description&quot; content=&quot;네이버 메인에서 다양한 정보와 유용한 컨텐츠를 만나 보세요&quot;/&gt; &lt;meta property=&quot;og:title&quot; content=&quot;네이버&quot;&gt; &lt;meta property=&quot;og:url&quot; content=&quot;https://www.naver.com/&quot;&gt; &lt;meta property=&quot;og:image&quot; content=&quot;https://s.pstatic.net/static/www/mobile/edit/2016/0705/mobile_212852414260.png&quot;&gt; &lt;meta property=&quot;og:description&quot; content=&quot;네이버 메인에서 다양한 정보와 유용한 컨텐츠를 만나 보세요&quot;/&gt; &lt;meta name=&quot;twitter:card&quot; content=&quot;summary&quot;&gt; <br>/ ... /</pre><p>결과는 앞서 살펴본 예제와 동일합니다.</p><p>스레드를 생성하는 방식과 비교해, GCD는 시스템이 스레드를 관리함으로써 스레드 관리에 대한 신경을 쓰지 않을 수 있었습니다.</p><blockquote>지금은 간단한 예제를 실행해 보았지만, 예제가 더 많이 복잡해지면 차이는 더 분명해질 것으로 생각합니다.</blockquote><p>방금 살펴본 GCD 역시 한계를 가지고 있는데요, GCD도 concurrent dispatch queue에 의해 예약된 작업이 스레드를 차단할 경우, 시스템은 대기 중인 다른 병렬작업을 실행할 추가 스레드를 생성하게 됩니다.</p><p>위에서 작성한 코드 예제에서는 아래와 같이 custom concurrent queue를 생성해 주었는데요,</p><pre>private let networkRequestQueue = DispatchQueue(<br>  label: &quot;com.example.networkRequestQueue&quot;<br>)</pre><p>custom concurrent queue를 과도하게 생성할 경우, 각각의 dispatch queue는 스레드 리소스를 사용하기 때문에 스레드를 생성하게 되어 앞서 살펴본 그래프와 같이</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vN_ujRwTLxuet3Zi" /><figcaption>출처 : <a href="https://www.baeldung.com/cs/servers-threads-number?ref=noah-ios.dev">https://www.baeldung.com/cs/servers-threads-number</a></figcaption></figure><p>많은 스레드간 문맥 전환으로 인한 성능저하로 이어질 수 있습니다.</p><p>더 많은 스레드가 실행되면 문맥 전환이 더 자주 발생하고, 이로 인해 시스템의 부담이 더 커지게 됩니다. 이것이 바로 “thread-explosion”입니다.</p><blockquote>thread-explosion: 시스템 내의 스레드가 많아져 스레드 스위칭 등의 오버헤드가 발생하게 되는 현상</blockquote><p>따라서 <a href="https://developer.apple.com/documentation/dispatch/dispatchqueue?ref=noah-ios.dev#3136752">Apple의 문서</a>에서는 custom queue를 생성하는 대신 global concurrent dispatch queue에 작업을 제출해 스레드 수를 적절하게 유지하도록 가이드하고 있습니다.</p><p>또한 DispatchQueue는 First In First Out 특성을 가진 Queue이기 때문에 <a href="https://en.wikipedia.org/wiki/Priority_inversion?ref=noah-ios.dev">우선순위 역전 현상</a>이 발생할 수 있으며, 클로저를 이용해 명시적으로 작업을 제출하는 방식이기에 작업을 기다리는 순서가 복잡해지게 되면 클로저들이 중첩되는 상황이 생기게 되어 개발자로 하여금 코드의 흐름을 따라가기 어렵게 만드는 문제가 있습니다.</p><p>이러한 문제들을 해결하기 위해 Swift Concurrency가 등장하게 되는데요,</p><p>앞서 살펴본 예제, Swift Concurrency를 이용해 다시 작성해 볼까요?</p><h3>Swift Concurrency</h3><p>먼저 실행되기 원하는 작업의 단위를 Task를 이용해 지정해주도록 하겠습니다.</p><pre>final class NetworkRequestManager {<br>  private var networkRequestTask: Task&lt;Void, Never&gt;? = nil<br>}</pre><p>네트워크 요청을 동기적으로 한 후에 응답을 콘솔에 출력하는 함수를 추가하도록 하겠습니다.</p><pre>final class NetworkRequestManager {<br>  private var networkRequestTask: Task&lt;Void, Never&gt;? = nil<br>	<br>  private func fetchAndPrintHTML(from url: URL) {<br>    let responseData = try! Data(contentsOf: url)<br>    print(String(data: responseData, encoding: .utf8)!)<br>  }<br>}</pre><p>이제 해당 함수를 실행하기 위해 task를 생성하는 함수를 추가해 보겠습니다.</p><pre>final class NetworkRequestManager {<br>  var networkRequestTask: Task&lt;Void, Never&gt;? = nil<br>	<br>  func startRequest() {<br>    self.networkRequestTask = Task {<br>      self.fetchAndPrintHTML(from: URL(string: &quot;https://www.naver.com&quot;)!)<br>    }<br>  }<br>	<br>  private func fetchAndPrintHTML(from url: URL) {<br>    let responseData = try! Data(contentsOf: url)<br>    guard Task.isCancelled == false<br>    else { return }<br><br>    print(String(data: responseData, encoding: .utf8)!)<br>  }<br>	<br>  deinit {<br>    self.networkRequestTask?.cancel()<br>    self.networkRequestTask = nil<br>  }<br>}</pre><p>네트워크 요청을 한 이후에 Task가 취소되었는지 여부를 확인하고 취소가 되지 않았다면 콘솔에 응답을 출력합니다.</p><p>작성한 코드 예제를 실행해 보도록 하겠습니다.</p><pre>let networkRequestManager = NetworkRequestManager()<br>networkRequestManager.startRequest()<br><br>print(&quot;안녕하세요&quot;)<br><br>RunLoop.main.run()</pre><p>결과를 확인해봅시다.</p><pre>안녕하세요<br>   &lt;!doctype html&gt; &lt;html lang=&quot;ko&quot; class=&quot;fzoom&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta name=&quot;Referrer&quot; content=&quot;origin&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=1190&quot;&gt; &lt;title&gt;NAVER&lt;/title&gt; &lt;meta name=&quot;apple-mobile-web-app-title&quot; content=&quot;NAVER&quot;/&gt; &lt;meta name=&quot;robots&quot; content=&quot;index,nofollow&quot;/&gt; &lt;meta name=&quot;description&quot; content=&quot;네이버 메인에서 다양한 정보와 유용한 컨텐츠를 만나 보세요&quot;/&gt; &lt;meta property=&quot;og:title&quot; content=&quot;네이버&quot;&gt; &lt;meta property=&quot;og:url&quot; content=&quot;https://www.naver.com/&quot;&gt; &lt;meta property=&quot;og:image&quot; content=&quot;https://s.pstatic.net/static/www/mobile/edit/2016/0705/mobile_212852414260.png&quot;&gt; &lt;meta property=&quot;og:description&quot; content=&quot;네이버 메인에서 다양한 정보와 유용한 컨텐츠를 만나 보세요&quot;/&gt; &lt;meta name=&quot;twitter:card&quot; content=&quot;summary&quot;&gt; <br>/ ... /</pre><p>역시 결과는 앞서 살펴본 예제와 동일합니다.</p><p>GCD와 비교해 어떤가요?</p><p>코드 외적으로는 동기적인 코드를 작성하는 것과 비슷하게 코드를 작성할 수 있게 되었습니다.</p><p>또한, 컴파일 단계에서 데이터 레이스와 관련된 에러를 발생시켜 코드 작성 실수로 발생할 수 있는 문제를 해결할 수 있습니다.</p><p>이와 함께, 이전 GCD가 가지고 있던 문제인 스레드가 과도하게 생성되어 발생하는 thread-explosion 문제를 suspend point(await)에서 스레드 간 문맥 전환이 아닌, 작업의 재개 여부를 추적하는 가벼운 객체인 continuation 간 전환을 하도록 하여, 스레드를 차단하지 않고 함수 호출 정도의 비용만 지불하도록 하였습니다.</p><p>더불어, 프로세스의 스레드 수를 CPU 코어 수만큼 생성하도록 제한하여 thread-explosion 문제를 해결하였습니다.</p><blockquote><a href="https://developer.apple.com/videos/play/wwdc2021/10254/?time=528&amp;ref=noah-ios.dev">WWDC-21 Swift concurrency: Behinde the scenes 참조</a></blockquote><p>또한 GCD와 달리 작업이 실행되는 순서가 FIFO가 아니기 때문에 먼저 추가된 작업이 실행되고 있을 때 실행되고 있는 작업보다 우선순위가 더 높은 작업이 추가되면 해당 작업을 먼저 실행함으로써 우선순위 역전 문제를 해결하였습니다.</p><h3>마치며</h3><p>이번 글에서는 Swift Concurrency 이전에는 동시성 프로그래밍을 구현하기 위해 어떠한 도구들을 사용했는지, 어떠한 맥락으로 동시성 프로그래밍을 도와주는 도구들이 등장하게 되었는지 살펴보았습니다.</p><p>이를 통해 Swift Concurrency가 등장한 배경을 이해하는 데 여러분께 도움이 되었으면 좋겠습니다.</p><p>Swift Concurrency 역시 Swift와 함께 발전하는 기술이기에 앞으로 추가될 기능들이 더 기대가 됩니다.</p><p>긴 글 읽어주셔서 감사합니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50a224d14dc8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daily-monster/swift-concurrency-%EC%9D%B4%EC%A0%84%EC%9D%98-%EB%8F%99%EC%8B%9C%EC%84%B1-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D-50a224d14dc8">Swift Concurrency 이전의 동시성 프로그래밍</a> was originally published in <a href="https://medium.com/daily-monster">daily-monster</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[동시성과 병렬성의 차이]]></title>
            <link>https://medium.com/daily-monster/%EB%8F%99%EC%8B%9C%EC%84%B1%EA%B3%BC-%EB%B3%91%EB%A0%AC%EC%84%B1%EC%9D%98-%EC%B0%A8%EC%9D%B4-19b5843e34e7?source=rss-bb5cbd32d89------2</link>
            <guid isPermaLink="false">https://medium.com/p/19b5843e34e7</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Noah]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 09:02:06 GMT</pubDate>
            <atom:updated>2024-01-25T09:02:06.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sQ8NT3X1LPpBlhiR" /><figcaption>Photo by <a href="https://unsplash.com/@livrax?utm_source=medium&amp;utm_medium=referral">Liviu Rau</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>들어가며</h3><p>안녕하세요!<br>일간괴물의 목요괴물! 노아입니다 :)<br>Medium에서의 첫 글이네요 ㅎㅎ</p><p>이번 주제에서는 Swift Concurrency에 대해 자세히 알아보기에 앞서 동시성과 병렬성에 대한 개념을 잡아보려고 해요</p><p>코드를 다른 코드와 동시에 실행한다는 것은 무엇을 의미하는 걸까요?<br>Computer Science에서 ‘동시’라는 단어의 의미는 2개 이상의 사건이 정확히 같은 시간에 진행되는 것을 의미하는 “same-time”을 의미하는걸까요?<br><br>그럼 시작해보시죠!</p><p>우리가 작성하는 대부분의 코드는 동시성이 없는, 단일 스레드에서 실행되는 코드<br>아래와 같이 동기적인 방식으로 한번에 한줄, 한줄 씩, 한 함수씩 실행돼요</p><pre>func getFullName() {<br> let givenName = getGivenName()<br> let familyName = getFamilyName()<br> print(“\\(givenName) \\(familyName)”)<br>}<br><br>func getGivenName() -&gt; String {<br> print(&quot;What&#39;s your given name?&quot;)<br> return readLine() ?? &quot; - &quot;<br>}<br><br>func getFamilyName() -&gt; String {<br> print(&quot;What&#39;s your family name?&quot;)<br> return readLine() ?? &quot; - &quot;<br>}<br><br>getFullName()</pre><ul><li>위 코드는 readLine() 함수에서 사용자의 입력을 받을 때까지 대기하고 있을 거예요</li><li>물론 사용자의 입력을 받을 때까지 대기할 동안 아무런 작업도 하지 못합니다.</li></ul><p>위 처럼 오래걸리는 작업 혹은 프로그램이 CPU 혹은 스레드를 계속해서 점유하지 않고 원활하게 실행되도록 하려면 동시성을 활용해야해요</p><p>CPU는 여러 작업을 동시에 수행할 수 있습니다.</p><p>여러작업을 동시에 수행한다는 것은 무엇을 말하는걸까요?</p><p>여러작업을 동시에 수행한다는 것은 <strong>하나의 작업</strong>을 동시(same-time)에 수행하는 것이 아닌, <strong>여러 작업</strong>을 번갈아 실행하며 동시(same-time)에 수행되는 것 처럼 보이는 것을 의미해요</p><p>한 개의 Core를 가진 CPU에서도 한 개 이상의 스레드를 동시에(번갈아 가며) 실행하며 멀티 스레딩 환경을 구현할 수 있어요</p><blockquote>그렇다면 여러 코어를 가진 CPU에서는 어떨까요?</blockquote><p>여러 CPU Core를 가진 환경에서는 병렬로 여러 스레드를 실행할 수 있는데요,</p><h4>동시성과 병렬성의 차이</h4><p>이쯤에서 동시성과 병렬성의 차이에 대해 정리하면 좋을 것 같아요</p><p>동시성은 위에서 말했던 것처럼 여러 작업을 번갈아가며 수행하는 것을 의미해요</p><p>병렬성은 여러 작업을 same-time에 수행한다는 것을 의미해요</p><h4>Thread Safety</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MF7Qrk3CTxAtkkVQQevcRA.png" /></figure><p>여러파일에서 한줄 한줄 씩 파일을 읽어서 특정 키워드를 찾아 일치한 키워드를 결과 파일에 기록하는 상황을 가정해보겠습니다.</p><blockquote>색이 다른 각각의 박스는 다른 스레드에서 실행되고 있다고 가정합니다.</blockquote><p>위 작업은 어떠한 잠재적인 문제를 가지고 있을까요?</p><p>여러 스레드가 정확하게 same-time에 일치한 특정 키워드를 기록하려고 할 때 데이터 레이스가 발생하게 됩니다.</p><p>기록하는 작업이 원자적으로 이루어진다는 전제하에서는 동시적으로 일치한 항목을 기록하려고 하면 괜찮지만, 병렬로 일치한 항목을 기록할 경우 데이터의 일관성이 깨지게 되는 문제가 발생할 수 있어요</p><p>위와 같은 상황 이외에도 멀티스레드 환경에서는 적어도 하나가 쓰기 연산을 수행할 때 데이터 레이스의 위험이 따르는데요,</p><p>예측 불가능한 결과를 방지하기 위해 멀티스레드 환경에서 작업할 때는 데이터 레이스를 피하기 위한 적절한 동기화 메커니즘을 사용해야 해요.</p><p>예를 들어 뮤텍스(Mutex)나 세마포어(Semaphore) 같은 도구를 사용하여 공유 자원에 대한 접근을 조절하고, 원자성을 보장할 수 있는 연산을 사용해야합니다.</p><h4>마치며</h4><p>이번 시간에는 동시성과 병렬성의 차이에 대해 알아보았는데요, Swift Concurrency에서는 앞서 살펴본 문제들을 어떻게 해결했는지 다음 글들을 통해서 알아보도록 하겠습니다 :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19b5843e34e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daily-monster/%EB%8F%99%EC%8B%9C%EC%84%B1%EA%B3%BC-%EB%B3%91%EB%A0%AC%EC%84%B1%EC%9D%98-%EC%B0%A8%EC%9D%B4-19b5843e34e7">동시성과 병렬성의 차이</a> was originally published in <a href="https://medium.com/daily-monster">daily-monster</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>