多线程中的共享内存

时间:2014-10-27 05:18:19

标签: c# multithreading

程序是使用线程计算字符串中的元音数量。

counter =线程数。

元数的数量在DictionaryEntry中维护,并且由多个线程访问。帽子和小写字母组合在一起。 编码是根据以下样本输入和输出。

O / P:

输入计数器数量: 2

输入计数器1的文字: Everbody得到了一些时间

输入计数器2的文字: 一,二,三,四,五,六,七,八,九,十

给定文字中的元音数量为: a:2 e:14 i:5 o:6 u:1

我的计划到目前为止:

课程计划

{

    public static Dictionary<char, int> h = new Dictionary<char, int>();

    static void count(int s)
    {
        Console.WriteLine("Enter text for counter {0} :", s);
        string str = Console.ReadLine();
        char[] c = str.ToCharArray();
        int n = 1;

        for (int i = 0; i < c.Length; i++)
        {
            if ((char.ToLower(c[i]) == 'a') || (char.ToLower(c[i]) == 'e') || (char.ToLower(c[i]) == 'i') || (char.ToLower(c[i]) == 'o') || (char.ToLower(c[i]) == 'u'))
            {
                if (!h.ContainsKey(c[i]))
                {
                    for (int j = i + 1; j < c.Length; j++)
                    {

                        if (c[i] == c[j])
                        {
                            n++;
                        }

                    }
                    h.Add(c[i], n);
                }
                n = 1;
            }
        }
        foreach (var v in h.Keys)
        {
            Console.WriteLine("{0}:{1}", v, h[v]);
        }
    }
    static void Main(string[] args)
    {
        int s=0;
        count(s);
        for (int i = 0; i < 2; i++)
        {
            Thread t1 = new Thread(() => count(i + 1));
            t1.Start();
            t1.Join();
        }

        Console.Read();
    }
}

1 个答案:

答案 0 :(得分:1)

您当前的程序会因为从每个线程的控制台输入而出现问题,这不是最优雅的输入方式,我建议您进行以下更改:

  • 将输入作为ThreadStart委托的一部分传递,更好地创建所有输入的集合并使用并行foreach

现在您的字典会因多线程访问而中断,请改用

System.Collections.Concurrent.ConcurrentDictionary<TKey, TValue>

当然,您对API的调用将更改为TryAdd,与所有并发数据结构一样