C#,Parallel并行多线程计算,使用专门的Concurrent系列数据集

常规的 Hashtable 在并行计算时,会出现冲突错误!

Concurrent*** 是适合于并行计算的数据集系列

https://learn.microsoft.com/zh-cn/dotnet/api/system.collections.concurrent?view=net-9.0

提供多个线程安全的集合类,这些类应在多个线程同时访问集合时代替 System.CollectionsSystem.Collections.Generic 命名空间中的相应类型。

但是,不保证通过扩展方法或通过显式接口实现访问集合对象的元素是线程安全的,并且可能需要由调用方同步。

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| BlockingCollection<T> | 为实现 IProducerConsumerCollection<T>的线程安全集合提供阻塞和边界功能。 |
| ConcurrentBag<T> | 表示对象的线程安全无序集合。 |
| ConcurrentDictionary<TKey,TValue> | 表示可同时由多个线程访问的键/值对的线程安全集合。 |
| ConcurrentQueue<T> | 表示线程安全的先出 (FIFO) 集合。 |
| ConcurrentStack<T> | 表示线程安全最后一次传入 (LIFO) 集合。 |
| OrderablePartitioner<TSource> | 表示将可排序数据源拆分为多个分区的特定方式。 |
| Partitioner | 为数组、列表和可枚举提供常见的分区策略。 |
| Partitioner<TSource> | 表示将数据源拆分为多个分区的特定方式。 |

cs 复制代码
ConcurrentDictionary<string, int>[] hash = new ConcurrentDictionary<string, int>[N];
for (int i = 0; i < N; i++) hash[i] = new ConcurrentDictionary<string, int>();
// 并行计算方法
Parallel.For(0, records.Count, i =>
{
    EMRRecord emr = records[i];
    EMRInfo eri = new EMRInfo();
    eri.split_to_chapters(emr);
    foreach (EMRChapter ch in eri.chapters)
    {
        int div = division_by_name(ch.name);
        if (div < 0) continue;
        if (div >= N) continue;
        for (int j = 0; j < ch.content.Length; j++)
        {
            string s1 = ch.content.Substring(j, 1);
            if (Char.IsLetter(s1[0]) || StringHelper.IsChinese(s1))
            {
                if (!hash[div].ContainsKey(s1))
                {
                    hash[div].TryAdd(s1, 1);
                }
                else
                {
                    hash[div][s1] = (int)hash[div][s1] + 1;
                }
            }
        }
    }
});
相关推荐
gopyer2 分钟前
180课时吃透Go语言游戏后端开发2:Go语言中的变量
开发语言·游戏·golang·游戏后端开发
月月吃喝4 分钟前
【PyQt5】嵌套多线程数据交互实现
开发语言·qt·交互
匿名4598 分钟前
Lombok注解使用无效的情况(未能获得后端数据)
java·开发语言
徐子童26 分钟前
JVM高频面试题---GC垃圾回收
java·开发语言·jvm·面试题·gc·垃圾回收算法
AutomanLV36 分钟前
c# datagridview添加list内容
程序人生·c#
Z_z在努力40 分钟前
【数据结构】队列(Queue)全面详解
java·开发语言·数据结构
poemyang1 小时前
揭秘JUC:volatile与CAS,并发编程的两大基石
多线程·并发编程·java并发编程
qiu_zhongya2 小时前
iree 用C++来运行Qwen 2.5 0.5b
开发语言·c++·人工智能
汪宁宇2 小时前
giflib5.2.2 在Qt与VS C++中实现Gif缩放示例
开发语言·c++·qt
啊?啊?2 小时前
C/C++练手小项目之倒计时与下载进度条模拟
c语言·开发语言·c++