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;
                }
            }
        }
    }
});
相关推荐
Yeauty1 小时前
渲染成图再 CLI 拼接,还是进程内直推?Rust 帧到视频的两条路
开发语言·rust·音视频
geovindu2 小时前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
库克克2 小时前
【C++】set 与multiset
开发语言·c++
Wang's Blog3 小时前
Go-Zero项目开发34: 微服务超时控制与重试机制实践
开发语言·微服务·golang·go-zero
2zcode3 小时前
项目文档:基于MATLAB神经网络的心力衰竭预测与临床辅助决策系统研究
开发语言·神经网络·matlab·心力衰竭预测\
减瓦4 小时前
深入 Quarkus:云原生时代 Java 的重生之路
java·开发语言·云原生
杨运交4 小时前
[053][核心模块]Java枚举缓存与ORM集成实践
java·开发语言·缓存
2401_894915535 小时前
Geo优化系统源码部署搭建技术——PHP程序开发部署指南
开发语言·php
wuyk5555 小时前
67.嵌入式C语言进阶:结构体指针实战指南——STM32外设、传感器数据访问的高效技巧
c语言·开发语言·stm32·单片机
找磁材5 小时前
空心杯电机与永磁体
开发语言·磁性材料·钕铁硼·磁钢