Structured Concurrency क्या है
Structured concurrency का मतलब है कि काम के related pieces एक साथ neatly group किए गए हैं, ताकि वे सभी एक tidy unit के रूप में खत्म (या सभी cancelled) हों, अपने आप अलग बिखरने के बजाय।
Syntax
async let first = asyncFunction1()
async let second = asyncFunction2()
let results = await (first, second)
await withTaskGroup(of: ResultType.self) { group in
group.addTask { await work() }
for await result in group { /* use result */ }
}
Concurrent Work with async let
async let एक asynchronous operation तुरंत शुरू करता है और इसे function के बाकी हिस्से के साथ concurrently चलने देता है, जब तक इसकी value await न हो।
उदाहरण: Concurrent Work with async let
func fetchFirstName() async -> String {
return "Ada"
}
func fetchLastName() async -> String {
return "Lovelace"
}
async let first = fetchFirstName()
async let last = fetchLastName()
let fullName = await "\(first) \(last)"
print(fullName)
Login to try C/C++/Java/PHP code in the editor
Grouping Tasks with withTaskGroup
withTaskGroup आपको child tasks की एक dynamic संख्या जोड़ने देता है और उनके results को एक structured, awaitable unit के रूप में एक साथ collect करने देता है।
उदाहरण: Grouping Tasks with withTaskGroup
func square(_ n: Int) async -> Int {
return n * n
}
let total = await withTaskGroup(of: Int.self) { group in
for number in 1...4 {
group.addTask {
await square(number)
}
}
var sum = 0
for await result in group {
sum += result
}
return sum
}
print("Sum of squares: \(total)")
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. #}
आम गलतियां
- Related work के लिए
async letया एक task group से group करने के बजाय कई independentTask { }blocks launch करना, cancellation और error propagation को manage करना मुश्किल बनाते हुए। - यह भूल जाना कि
async letbindings declare होते ही concurrently चलती हैं, लेकिन हर एक को अपना result retrieve करने के लिए अब भीawaitकिया जाना चाहिए। - एक task group उपयोग करना लेकिन group के
with...TaskGroupblock खत्म होने से पहले इसकी सभी child tasks कोawaitकरना भूल जाना।
चैप्टर सारांश
async letएक function scope के अंदर कई asynchronous operations concurrently शुरू करता है।- हर
async letbinding को इसकी value retrieve करने के लिए await किया जाना चाहिए। - Task groups (
withTaskGroup) concurrent child tasks की एक dynamic संख्या को एक साथ manage करते हैं। - Structured concurrency किसी task की lifetime को इसे बनाने वाले scope से बांधती है, cancellation और error handling को predictable बनाते हुए।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: