如何为我的代码提供线程安全性

本文关键字:线程 安全性 代码 我的 | 更新日期: 2023-09-27 17:54:11

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);
        }
    }
}

我想并行化上面的代码。我需要对count()从0到10^9 - 1做10亿次运算。count()函数本身不与其他线程共享数据。然而,将结果从count()加到total不是线程安全的-每次运行程序的结果都不同。total必须存储一些不能存储在int类型中的整型值。我的问题有解决办法吗?

如何为我的代码提供线程安全性

下面是使用Sum(ParallelQuery<Int64>)将投影和求和结合起来的一行代码。

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

Parallel LINQ使这很容易:

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

试试这个:

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

您也可以使用标准的lock()