thkang
thkang

Reputation: 11533

how can I provide thread safety to my code?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Program
{
    class Program
    {
        static long total = 0;
        static long count(int row)
        {
            /* do_something .. every operation is thread safe here */
            return somevalue;
        }
        static void Main(string[] args)
        {
            Parallel.For(0, 10000000, i => //some big limit to test threading is working
            {
                total += count(i);
                // however, collecting 'somevalue' from 'count()' operation isn't thread safe.
            });

            Console.WriteLine(total);
        }
    }
}

I want to parallelize above code. I have to do one billion operation of count() from 0 to 10^9 - 1. the count() function itself shares no data with other threads. however, adding up results from count() to total ain't thread safe - the results differ every time I run the program. total has to store some integral value that can't be stored in int. Is there any solution to my problem?

Upvotes: 0

Views: 95

Answers (3)

Mattias Buelens
Mattias Buelens

Reputation: 20159

Here's a one-liner using Sum(ParallelQuery<Int64>) to combine the projection and the summation.

long total = ParallelEnumerable.Range(0, 10000000).Sum(row => count(row));

Upvotes: 3

CodesInChaos
CodesInChaos

Reputation: 108790

Parallel LINQ makes this easy:

ParallelEnumerable.Range(0, 10000000).Select(i=>count(i)).Sum()

Upvotes: 2

user959729
user959729

Reputation: 1177

Try this:

http://msdn.microsoft.com/en-us/library/system.threading.interlocked.increment(v=vs.100).aspx

You could also use the standard lock() too.

Upvotes: 0

Related Questions