Question

My goal is the following:

There is a certain range of integers, and I have to test every integer in that range for something random. I want to use multiple threads for this, and divide the work equally among the threads using a shared counter. I set the counter at the beginning value, and let every thread take a number, increase it, do some calculations, and return a result. This shared counter has to be incremented with locks, because otherwise there will be gaps / overlaps in the range of integers to test.

I have no idea where to start. Let's say I want 12 threads to do the work, I do:

for (int t = 0; t < threads; t++)
{
  Thread thr = new Thread(new ThreadStart(startThread));
}

startThread() isthe method I use for the calculations.

Can you help me on my way? I know I have to use the Interlocked class, but that's all….

Was it helpful?

Solution

Say you have an int field somewhere (initialized to -1 initially) then:

int newVal = Interlocked.Increment(ref theField);

is a thread-safe increment; assuming you don't mind the (very small) risk of overflowing the upper int limit, then:

int next;
while((next = Interlocked.Increment(ref theField)) <= upperInclusive) {
   // do item with index "next"
}

However, Parallel.For will do all of this a lot more conveniently:

Parallel.For(lowerInclusive, upperExclusive, i => DoWork(i));

or (to constrain to 12 threads):

var options = new ParallelOptions { MaxDegreeOfParallelism  = 12 };
Parallel.For(lowerInclusive, upperExclusive, options, i => DoWork(i));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top