微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何激发对共享资源的同时访问?

我正在创建一个对输入执行顺序处理的组件.由于它将托管在几个不同的进程中,我需要它是线程安全的.起初,我故意从代码中省略了线程安全性.现在是时候介绍一下了.

首先,我想引发一个错误,但是无法做到.以下是处理引擎代码的简化版本:

public Document Doorchestration(Document input)
{
    Document output = new Document();

    foreach (var orchestrationStep in m_orchestrationSteps)
    {
        var processor = GetProcessor(orchestrationStep).Clone();

        output = processor.Process(input);

        input = output;
    }

    return output;
}

处理器可以由我组织中的其他人开发,可以包括一些复杂的初始化.它们也可能是线程不安全的,所以我使用Prototype Pattern来获取它们的唯一实例,以避免线程问题.

为了测试这个功能,我使用了以下代码

for (int i = 0; i < 20000; i++)
{
    Thread t = new Thread(() => Testorchestration(i));
    t.Start();
}

void Testorchestration(int number)
{
    Document doc = new Document(string.Format("Test {0}",number));
    doc = Doorchestration(doc);
    if (doc.ToString().Substring(0,35) != strExpectedResult)
    {
        System.Console.WriteLine("Error: {0}",doc.ToString();
    }
}

我预计一些线程会与另一个线程发生冲突并混淆其结果,但令我惊讶的是,这并没有发生.

对此可能有一个简单而合理的解释,但它让我望而却步.或者只是代码太简单而导致两个线程同时摆弄输入/输出变量?

解决方法

查看 CHESS.

CHESS is a tool for finding and reproducing Heisenbugs in concurrent programs. CHESS repeatedly runs a concurrent test ensuring that every run takes a different interleaving. If an interleaving results in an error,CHESS can reproduce the interleaving for improved debugging. CHESS is available for both managed and native programs.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐