Short
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    은행창구 매니저 [STEP 3] woong, 준호 안녕하세요 엘림 @lina0322 ! 좀 늦었지만 STEP 3 PR 보냅니다. 이번에도 잘 부탁드립니다. ### 💡 Step 3 수행 중 핵심경험 1. 동기(Synchronous)와 비동기(Asynchronous)의 이해 2. 동시성 프로그래밍 개념의 이해 3. 동시성 프로그래밍을 위한 기반기술(GCD, Operation) 등의 이해 4. 스레드(Thread) 개념에 대한 이해 5. GCD를 활용한 동시성 프로그래밍 구현 6. 동기(Synchronous)와 비동기(Asynchronous) 동작의 구현 및 적용 ## 구현내용 ![은행창구 매니저 ClassDiagram](https://github.com/iOS-Woong/ios-bank-manager/blob/step-3/UML.jpg?raw=true) 1. BankBusiness * 은행 업무(예금, 대출)을 열거형으로 만들었습니다. * 랜덤 값을 반환하는 `allCases.randomElement()`메서드를 사용하기 위해 `CaseIterable` 프로토콜을 채택했습니다. 2. Customer * 고객이 원하는 업무(대출, 예금)를 구분하기 위해서 `BankBusiness` 타입의 인스턴스를 갖도록 하였습니다. 3. Banker * 불필요한 프로퍼티(`oneMillion`)를 없애기 위해 `Thread.sleep(forTimeInterval: Double)` 메서드를 지연함수로 채택하였습니다. * 은행원이 처리할 수 있는 업무(대출, 예금)를 구분하기 위해서 `BankBusiness` 타입의 인스턴스를 갖도록 하였습니다. 4. BankManager, ConsoleApp * 업무 별로 은행원을 따로 추가하기 위해서 기존 `addBankers(count: Int)` 메서드를 `addBankers(bankBusiness: BankBusiness, count: Int)`로 변경했습니다. * `addBankers()` 메서드를 호출하는 `ConsoleApp`의 `startBankByCreatingBankManager()` 메서드도 맞게 수정했습니다. 6. LinkedList, Queue * `deposit`을 담당하는 은행원과 `loan`을 담당하는 은행원의 처리업무가 동시에 처리되는 것을 방지하기 위해 접근가능 스레드의 수를 제한을 의도로 `DispatchSemaphore`를 활용하였습니다. * `DispatchSemaphore`의 `value`값을 활용하기 위해 큐에 담긴 `Element`의 개수에 접근해야했고, * 따라서,`count` 프로퍼티를 추가했습니다. 8. Bank * 총 업무시간(함수의 실행시간)을 측정하기 위한 저장 프로퍼티 `startTime`, `endTime`를 추가했습니다. * `startBankBusiness()` 메서드 내부 처음과 끝에서 `startTime`, `endTime` 에 시간을 설정해주고 `printClosingMessage()` 메서드 호출 시 `startTime`, `endTime` 사이의 interval 출력하도록 했습니다. * 기존 은행원 배열을 업무별로 은행원을 담은 Queue로 변경했습니다. 고객 업무 처리 시 은행원을 dequeue하여 은행원이 업무를 처리하도록 한 뒤 다시 enqueue하여 제일 마지막 순서로 가도록 했습니다. 이렇게하면 은행원이 순환하면서 업무를 처리할 수 있었습니다. * `DispatchSemaphore`는 자원에 접근할 수 있는 스레드의 수를 제어해주는 역할을 합니다. `startBankBusiness()` 메서드에서는 업무별로 `depositSemaphore`, `loanSemaphore`를 두어서 스레드의 수를 각 은행원의 수만큼 제한하도록 했습니다. * `DispatchGroup` 은 비동기적으로 처리되는 작업들을 그룹으로 묶어, 그룹 단위로 작업 상태를 추적할 수 있는 기능입니다. `startBankBusiness()` 메서드에서는 `DispatchGroup`으로 예금 업무 처리 작업과 대출 업무 처리 작업을 묶었습니다. 그리고 `wait()` 로 모든 작업이 끝났는 지를 확인해서 `printClosingMessage()` 를 호출하도록 했습니다. `wait()` 는 DispatchGroup의 작업이 끝나기를 기다리는 메서드입니다. * 업무 처리는 `DispatchQueue.global().async()` 로 구현하였습니다. 각각의 은행원이 새로운 스레드에서`global()` 다음 작업을 기다리지 않고 업무를 처리할 수 있도록 비동기로 `(async)` 만들어야 했기에 위 방식으로 구현하였습니다. --- step2 Customer 프로퍼티 number는 은행에 온 고객을 대기번호를 기준으로 생각하여 Int 타입으로 만들었습니다. Banker 고객 당 업무 처리 시간을 저장할 processingTimePerCustomer 프로퍼티 상수를 추가했습니다. processBankingBusiness() 메서드는 전달 받은 고객의 은행 업무를 usleep(700_000) 간격으로 진행하고 업무 시작과 업무 완료 시점에 메시지를 출력합니다. sleep의 경우, Int만 인자값으로 설정해줄 수 있기에 요구조건인 0.7초를 표현하기엔 부적절하다고 판단하였고, usleep에서는 1의 값은 1_000_000 분의 1초를 나타내므로 700_000으로 지정해주었을 때, 0.7초를 만들수 있겠다고 판단하여 usleep을 사용하였습니다. Bank 고객 대기열을 저장하기 위해 Queue<Customer> 타입의 customerQueue 프로퍼티를 추가했습니다. 은행원을 담아 둘 [Banker] 타입의 bankers 프로퍼티를 추가했습니다. 처리한 고객 수를 저장할 processedCustomerNumber, 총 업무시간을 저장할 processedTotalTime 프로퍼티를 추가했습니다. 고객 대기열에 고객을 추가하는 addCustomerToQueue() 메서드와 은행원 배열에 은행원을 추가하는 addBanker() 메서드를 만들었습니다. printClosingMessage() 메서드에는 업무 마감시 처리한 고객과 총 업무시간을 출력해주는 기능을 구현했습니다. NumberFormatter를 사용해서 예시 화면처럼 총 업무시간 출력 시 소수점 아래 두자리까지 무조건 보이도록 했습니다. processBankingBusinessOfCustomers() 메서드는 고객 대기열에서 한명씩 dequeue하여 Banker에게 전달하여 고객의 업무를 처리 할 수 있도록 구현하였습니다. BankManager Bank 의 인스턴스를 프로퍼티로 가지고, Bank를 관리하고 실행하기 위한 기능을 가진 구조체를 만들었습니다. addCustomers() 메서드에는 전달 받은 count만큼 Customer를 만들어서 bank에 추가해주는 기능을 구현했습니다. addBankers() 메서드에는 전달 받은 count만큼 Banker를 만들어서 bank에 추가해주는 기능을 구현했습니다. startBank() 메서드에는 bank 가 업무를 시작하도록 하는 기능을 구현했습니다. ConsoleAppMenu 콘솔앱에서 사용하는 메뉴를 열거형으로 만들었습니다. CaseIterable 프로토콜을 채택하면 열거형의 모든 값을 담은 컬렉션인 allCases를 사용할 수 있습니다. allCases를 활용해서 메뉴 목록을 출력해주는 `printMenuList()`` 타입 메서드를 구현했습니다. ConsolApp 콘솔앱을 실행하고 관리하기 위해 콘솔앱 구조체를 만들었습니다. inputMenu() 메서드와 start() 메서드에서는 재귀함수를 활용했습니다. 재귀 함수는 함수 안에서 스스로를 호출하는 형태를 말합니다. 재귀함수에서는 탈출 조건이 중요해서 그 부분을 신경써서 구현했습니다. inputMenu()메서드에서는 메뉴를 잘못 선택한 경우에 재귀함수를 호출합니다. start() 메서드에서는 고객 업무 처리가 끝나고 은행문이 닫히는 경우에 다시 메뉴를 다시 출력한 뒤 메뉴 입력을 받도록 재귀함수를 호출합니다. startBankByCreatingBankManager() 메서드에는 BankManger 인스턴스를 생성하고 10~30명 사이 숫자의 고객과, 은행원을 추가 한 뒤, 고객의 업무를 처리하는 기능을 구현했습니다. |**ConsoleApp작동**| |:---:| |![](https://i.imgur.com/UXiJMUG.gif)| ## 고민되었던 점 * `Array<Banker>` -> `Queue<Banker>`로 변경 - 기존에 은행원을 담고있던 배열을 큐타입으로 변경하였습니다. - 이유: while문 내부의 for문을 통해 `Banker` 배열을 순서대로 업무를 처리하도록 할 경우에 순환해서 업무를 처리하지 않았습니다. - 해결: 기존 은행원 배열을 업무별로 은행원을 담은 `Queue<Banker>` 로 변경했습니다. 고객 업무 처리 시 은행원을 `dequeue` 하여 은행원이 업무를 처리하도록 한 뒤 `enqueue` 하여 제일 마지막 순서로 가도록 했습니다. 이렇게하면 은행원이 순환하면서 업무를 처리할 수 있었습니다. ```swift // 변경 전 private var bankers: [Banker] = [] while customerQueue.isEmpty == false { for banker in bankers { guard let customer = customerQueue.dequeue() else { break } banker.processBankingBusiness(of: customer) self.totalCustomerNumber += 1 self.totalTime += banker.processingTimePerCustomer } } // 변경 후 private var depositBankerQueue: Queue<Banker> = Queue() private var loanBankerQueue: Queue<Banker> = Queue() while customerQueue.isEmpty != true { guard let customer: Customer = customerQueue.dequeue() else { return } switch customer.bankBusiness { case .deposit: guard let banker: Banker = self.depositBankerQueue.dequeue() else { return } DispatchQueue.global().async(group: group) { depositSemaphore.wait() banker.processBankingBusiness(of: customer) depositSemaphore.signal() } self.totalCustomerCount += 1 self.depositBankerQueue.enqueue(banker) case .loan: guard let banker: Banker = self.loanBankerQueue.dequeue() else { return } DispatchQueue.global().async(group: group) { loanSemaphore.wait() banker.processBankingBusiness(of: customer) loanSemaphore.signal() } self.totalCustomerCount += 1 self.loanBankerQueue.enqueue(banker) } } ``` ## 조언을 얻고 싶은 부분 * `struct Bank` - 이번에 비동기 처리하도록 코드를 수정하니 아래 그림과 같은 컴파일 에러가 발생했습니다. ![](https://i.imgur.com/LyY9q8P.png) - 클로저 값 캡처와 관련된 문제인거 같은데 아래와 같이 bank 의 프로퍼티를 변경하는 부분을 클로저 표현 밖으로 이동했습니다. ```swift // 수정 전 while customerQueue.isEmpty != true { guard let customer: Customer = customerQueue.dequeue() else { return } switch customer.bankBusiness { case .deposit: DispatchQueue.global().async(group: group) { depositSemaphore.wait() guard let banker: Banker = self.depositBankerQueue.dequeue() else { return } banker.processBankingBusiness(of: customer) self.totalCustomerCount += 1 self.depositBankerQueue.enqueue(banker) depositSemaphore.signal() } // 수정 후 while customerQueue.isEmpty != true { guard let customer: Customer = customerQueue.dequeue() else { return } switch customer.bankBusiness { case .deposit: guard let banker: Banker = self.depositBankerQueue.dequeue() else { return } DispatchQueue.global().async(group: group) { depositSemaphore.wait() banker.processBankingBusiness(of: customer) depositSemaphore.signal() } self.totalCustomerCount += 1 self.depositBankerQueue.enqueue(banker) ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully