Actors क्या हैं
एक actor एक special तरह का type है जो एक समय में सिर्फ एक code piece को इसके data छूने देता है, ताकि अगर कई चीज़ें एक साथ इसका उपयोग करने की कोशिश करें तो कुछ भी mix up न हो।
In this page:
Syntax
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
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)")
Login to try C/C++/Java/PHP code in the editor
Why Actors Prevent Data Races
चूंकि एक actor एक समय में सिर्फ एक task को अपने methods चलाने देता है, इसके state modify करने वाली concurrent calls अपने आप serialized हो जाती हैं, corrupted या inconsistent data रोकते हुए।
उदाहरण: Why Actors Prevent Data Races
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)")
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
awaitके बिना सीधे किसी actor की property या method access करने की कोशिश करना; actor के state तक बाहर से सभी access asynchronous होनी चाहिए।- यह भूल जाना कि एक actor के अपने internal methods इसकी properties को सीधे access कर सकते हैं, बिना
awaitके, क्योंकि वे पहले से actor के isolation के अंदर चल रहे हैं। - 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: