15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

class Camera<br />

{<br />

public readonly int CameraID;<br />

public Camera (int cameraID) { CameraID = cameraID; }<br />

// Get image from camera: return a simple string rather than an image<br />

public string GetNextFrame()<br />

{<br />

Thread.Sleep (123); // Simulate time taken to get snapshot<br />

return "Frame from camera " + CameraID;<br />

}<br />

}<br />

To obtain a composite image, we must call GetNextFrame on each of four camera<br />

objects. Assuming the operation is I/O-bound, we can quadruple our frame rate with<br />

parallelization—even on a single-core machine. PLINQ makes this possible with<br />

minimal programming effort:<br />

Camera[] cameras = Enumerable.Range (0, 4) // Create 4 camera objects.<br />

.Select (i => new Camera (i))<br />

.ToArray();<br />

while (true)<br />

{<br />

string[] data = cameras<br />

.AsParallel().AsOrdered().WithDegreeOfParallelism (4)<br />

.Select (c => c.GetNextFrame()).ToArray();<br />

Console.WriteLine (string.Join (", ", data)); // Display data...<br />

}<br />

GetNextFrame is a blocking method, so we used WithDegreeOfParallelism to get the<br />

desired concurrency. In our example, the blocking happens when we call Sleep; in<br />

real life it would block because fetching an image from a camera is I/O-intensive<br />

rather than CPU-intensive.<br />

Calling AsOrdered ensures the images are displayed in a consistent<br />

order. Because there are only four elements in the sequence,<br />

this would have a negligible effect on performance.<br />

Changing the degree of parallelism<br />

You can call WithDegreeOfParallelism only once within a PLINQ query. If you need<br />

to call it again, you must force merging and repartitioning of the query by calling<br />

IsParallel() again within the query:<br />

"The Quick Brown Fox"<br />

.AsParallel().WithDegreeOfParallelism (2)<br />

.Where (c => !char.IsWhiteSpace (c))<br />

.AsParallel().WithDegreeOfParallelism (3) // Forces Merge + Partition<br />

.Select (c => char.ToUpper (c))<br />

PLINQ | 885<br />

Parallel<br />

Programming

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!