← Back to Swift Course | Chapter 13: Concurrency | Lesson 3 of 6

Actors क्या हैं

एक actor एक special तरह का type है जो एक समय में सिर्फ एक code piece को इसके data छूने देता है, ताकि अगर कई चीज़ें एक साथ इसका उपयोग करने की कोशिश करें तो कुछ भी mix up न हो।
Syntax
swift
actor ActorName {
    private var state: Type = initialValue

    func method() {
        state = newValue
    }
}

let instance = ActorName()
await instance.method()

Declaring and Using an Actor

एक actor एक class जैसा दिखता है लेकिन इसके mutable state तक access को अपने आप serialize करता है, बाहर से access होने पर await मांगते हुए।

उदाहरण: Declaring and Using an Actor

markup
actor Counter {
    private var value = 0
    func increment() {
        value += 1
    }
    func getValue() -> Int {
        return value
    }
}

let counter = Counter()
await counter.increment()
await counter.increment()
let current = await counter.getValue()
print("Counter value: \(current)")

Why Actors Prevent Data Races

चूंकि एक actor एक समय में सिर्फ एक task को अपने methods चलाने देता है, इसके state modify करने वाली concurrent calls अपने आप serialized हो जाती हैं, corrupted या inconsistent data रोकते हुए।

उदाहरण: Why Actors Prevent Data Races

markup
actor BankAccount {
    private var balance = 100
    func deposit(_ amount: Int) {
        balance += amount
    }
    func currentBalance() -> Int {
        return balance
    }
}

let account = BankAccount()
await account.deposit(50)
await account.deposit(25)
let balance = await account.currentBalance()
print("Balance: \(balance)")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. await के बिना सीधे किसी actor की property या method access करने की कोशिश करना; actor के state तक बाहर से सभी access asynchronous होनी चाहिए।
  2. यह भूल जाना कि एक actor के अपने internal methods इसकी properties को सीधे access कर सकते हैं, बिना await के, क्योंकि वे पहले से actor के isolation के अंदर चल रहे हैं।
  3. Actors को classes के साथ confuse करना; actors specifically concurrent code में data races रोकने के लिए अपने mutable state तक access serialize करते हैं।
चैप्टर सारांश
  • actor एक reference type declare करता है जो concurrent data races से इसके mutable state को protect करता है।
  • बाहर से किसी actor की properties और methods तक access के लिए await चाहिए।
  • Actor के अपने methods के अंदर चलने वाला code इसके state को सीधे access कर सकता है, बिना await के।
  • Actors safe concurrent state के लिए Swift का built-in solution हैं, manual locks को replace करते हुए।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.