Skip to main content
 首页 » 编程设计

c#之多线程会减慢整体字典访问速度

2024年02月24日15mfryf

我正在分析一个 C# 应用程序,它看起来像两个线程,每个线程调用 Dictionary<>.ContainsKey()在两个独立但相同的词典(只有两个项目)上各执行 5000 次是一个线程调用 Dictionary<>.ContainsKey() 的两倍慢在单个词典上 10000 次。

我正在使用名为 JetBrains dotTrace 的工具测量“线程时间”。我明确地使用相同数据的副本,因此我没有使用任何同步原语。 .NET 是否有可能在幕后进行一些同步?

我有一台双核机器,有三个线程在运行:一个被阻塞使用 Semaphore.WaitAll()而工作是在优先级设置为 ThreadPriority.Highest 的两个新线程上完成的.

明显的罪魁祸首,例如,实际上没有并行运行代码,并且没有使用发布版本已被排除。

编辑:

人们想要代码。那么好吧:

    private int ReduceArrayIteration(VM vm, HeronValue[] input, int begin, int cnt) 
    { 
        if (cnt <= 1) 
            return cnt; 
 
        int cur = begin; 
 
        for (int i=0; i < cnt - 1; i += 2) 
        { 
            // The next two calls are effectively dominated by a call  
            // to dictionary ContainsKey 
            vm.SetVar(a, input[begin + i]); 
            vm.SetVar(b, input[begin + i + 1]); 
            input[cur++] = vm.Eval(expr); 
        } 
 
        if (cnt % 2 == 1) 
        { 
            input[cur++] = input[begin + cnt - 1]; 
        } 
 
        int r = cur - begin; 
        Debug.Assert(r >= 1); 
        Debug.Assert(r < cnt); 
        return r; 
    } 
 
    // From VM 
    public void SetVar(string s, HeronValue o) 
    { 
        Debug.Assert(o != null); 
        frames.Peek().SetVar(s, o); 
    } 
 
    // From Frame 
    public bool SetVar(string s, HeronValue o) 
    { 
        for (int i = scopes.Count; i > 0; --i) 
        { 
            // Scope is a derived class of Dictionary 
            Scope tbl = scopes[i - 1]; 
            if (tbl.HasName(s)) 
            { 
                tbl[s] = o; 
                return false; 
            } 
        } 
        return false; 
    } 

现在是线程生成代码,可能会延迟:

public static class WorkSplitter 
{ 
    static WaitHandle[] signals; 
 
    public static void ThreadStarter(Object o) 
    { 
        Task task = o as Task; 
        task.Run(); 
    } 
 
    public static void SplitWork(List<Task> tasks) 
    { 
        signals = new WaitHandle[tasks.Count]; 
        for (int i = 0; i < tasks.Count; ++i) 
            signals[i] = tasks[i].done; 
        for (int i = 0; i < tasks.Count; ++i) 
        { 
            Thread t = new Thread(ThreadStarter); 
            t.Priority = ThreadPriority.Highest; 
            t.Start(tasks[i]); 
        } 
        Semaphore.WaitAll(signals); 
    }         
} 

请您参考如下方法:

即使 Dictionary 中有任何锁定(没有),它也不会影响您的测量,因为每个线程都使用一个单独的线程。运行此测试 10,000 次不足以获得可靠的计时数据,ContainsKey() 只需要 20 纳秒左右。您至少需要数百万次才能避免调度工件。