2

我有一棵树,T,节点,N。T 代表我正在监视的程序所做的所有内存分配和释放的记录。GUI 检查“计数”和“字节”

public class Node
{
    private Dictionary<int, Node> Children = new Dictionary<int, Node>();
    private int count; // Total allocs for all _leaves_ below
    private int bytes; // Total bytes allocated for all _leaves_ below

    protected void Instantiate( StackTrace stackTrace, int index ) { ... }
    protected void Increment( StackTrace stackTrace, int size, int index ) { ... }
    protected void Decrement( StackTrace stackTrace, int size, int index ) { ... }
}

public class Root : Node
{
    private void UpdateTree( StackTrace[] stackTraces ) { ... }
}

我的监控线程将交给我的树管理器一批堆栈跟踪,我的树管理器(如果堆栈被标记为分配)通过并为堆栈跟踪中的每个方法在树上创建一个节点(如果它没有已经存在),一直到 system32.dll。这工作正常。

完成此操作后,我将尝试并行更新树(不起作用):

private void UpdateTree( StackTrace[] stackTraces )
{
    ForEach(stackTrace in stackTraces)
    {
        if (HasntBeenInstantiated(stackTrace))
            Instantiate(stackTrace, 0);
    }

    Parallel.ForEach (allocs, alloc =>
    {
        if (alloc is AllocationEvent)
            T.Increment(alloc.stack, alloc.size, 0);
        else if (alloc is DeallocationEvent)
            T.Decrement(alloc.stack, alloc.size, 0);
    });
}

private void Instantiate( Stack stack, int size, int index )
{
    if (++index < stack.Length)
        GetOrAddNewChild(stack[index]).Instantiate(stack, index);
}

private void Increment( Stack stack, int size, int index )
{
    Interlocked.Increment(ref count);
    Interlocked.Add(ref bytes, size);

    if (++index < stack.Length)
        GetChild(stack[index]).Increment(stack, index);
}

private void Decrement( Stack stack, int size, int index )
{
    Interlocked.Decrement(ref count);
    Interlocked.Add(ref bytes, -size);

    if (++index < stack.Length)
        GetChild(stack[index]).Decrement(stack, index);
}

在每批中,我保证任何叶节点的分配事件都比释放事件多。但不知何故,在处理一批之后,我有时会在某些节点上出现负计数和/或负字节。 上面有什么不正确的吗?

笔记:

我避免使用锁和互斥锁,因为更新是无滞后的。只要所有数据都正确输入,每批结束时数字应该是正确的。

编辑:

结果是传入的数据有错误。

4

0 回答 0