Parallel.For क्या है
Parallel.For किसी loop के turns को एक साथ कई workers में बांट देता है, जैसे दोस्तों का एक group जिसमें हर एक अलग कमरा साफ़ करता है। यह बड़े jobs को तेज़ी से खत्म कर सकता है।
In this page:
Syntax
Parallel.For(start, endExclusive, i =>
{
// body runs concurrently for each i
});
Parallel.For
Parallel.For loop iterations को कई threads में concurrently चलाता है, CPU-bound काम के लिए उपयोगी जहां iterations एक-दूसरे पर निर्भर नहीं करते।
यह data-parallel tasks के लिए manually threads manage करने का एक सरल विकल्प है। चूंकि iterations क्रम से बाहर और concurrently चलते हैं, shared mutable state को सुरक्षित या टाला जाना चाहिए।
Warning:
Parallel.For के अंदर बिना synchronization के किसी shared variable को सीधे increment न करें — यह race conditions का कारण बनता है।उदाहरण: Parallel.For
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
int total = 0;
Parallel.For(1, 6, i =>
{
Interlocked.Add(ref total, i);
});
Console.WriteLine($"Total: {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. #}
आम गलतियां
Parallel.Forके अंदरtotal += iसे किसी shared variable को update करना, जो एक race condition है;Interlocked.Addया एकlockका उपयोग करें।- यह मान लेना कि iterations order में चलते हैं, जबकि वे कई threads पर चलते हैं इसलिए printed lines जैसे results किसी भी order में आते हैं।
- यह उम्मीद करना कि end value शामिल होगी, जबकि
Parallel.For(1, 6, ...)1 से 5 तक चलता है क्योंकि upper bound exclusive है।
चैप्टर सारांश
asyncऔरawaitcode को बिना block किए काम का इंतज़ार करने देते हैं।TaskऔरTask<T>asynchronous operations को represent करते हैं।ConfigureAwait,CancellationToken, औरParallel.Forasynchronous और parallel काम को control और cancel करते हैं।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: