Skip to main content

Practice ยท 1 of 2

Parallel scan with early exit

CHALLENGE
Difficulty: advanced+25 XP

Implement static int FirstMatch(int[] data, Func<int, bool> predicate, int workers) that finds the first index (lowest i) where predicate(data[i]) is true, running the scan in parallel chunks โ€” using Parallel.For with a shared 'found index' guarded by Interlocked.CompareExchange so only a LOWER index ever wins, and stopping other iterations once found (loopState.Stop()). Return -1 if absent. The test counts predicate invocations: without Stop() the full scan runs all 10 million calls for a match at index 5 โ€” the test requires fewer than 1 million.

Back to lesson: Practice: Parallel drills