c# - 为什么线程连接在此示例中表现不同?

标签 c# multithreading lambda thread-safety

更新的问题更加通用:

我有以下代码。当交换threads[i].Join()的位置时,你会得到不同的输出。

static void ThreadedWorker(int startIndex, int endIndex)
{
    Console.WriteLine("Working from results[ " + startIndex +"] to results["+endIndex+"]");
}

static void Main(string[] args)
{
    int threadCount = System.Environment.ProcessorCount;
    int calculationCount = 500; //the number of array elements we'd be iterating over if we were doing our work
    int threadDataChunkSize = calculationCount / threadCount;
    if (threadDataChunkSize < 1) threadDataChunkSize = 1; //just in case we have loads of threads

    Thread[] threads = new Thread[threadCount];
    for (int i = 0; i < threadCount; i++)
    {
        threads[i] = new Thread(() => ThreadedWorker(threadDataChunkSize * i, threadDataChunkSize*(i+1)));
        threads[i].Start();
        //threads[i].Join(); //****Uncomment for correct behaviour****
    }

    for (int i = 0; i < threadCount; i++)
    {
        //threads[i].Join(); //****Uncomment for incorrect behaviour****
    }

    Console.WriteLine("breakhere");
}

Join() 处于第一个循环中时,创建顺序行为,您将获得输出

Working from results[ 0] to results[125]
Working from results[ 125] to results[250]
Working from results[ 250] to results[375]
Working from results[ 375] to results[500]

Join() 处于第二个循环中时,创建并行行为,您会得到如下不确定性输出:

Working from results[ 375] to results[500]
Working from results[ 375] to results[500]
Working from results[ 500] to results[625]
Working from results[ 500] to results[625] (i is sometimes more than it should ever be!)

我怀疑 lambda 表达式以某种方式导致了问题。希望这种改写也表明这不是边界错误计算,或对我的数组的其他滥用!


最初的问题不太通用,并使用 startIndex 和 endIndex 来迭代正在工作的字节数组。我将 ThreadedWorker 描述为“不工作”,因为它似乎有时会更新结果数组,有时则不会。现在看来它被调用了,但是 startindex 和 endindex 被破坏了。

最佳答案

启动每个线程后、启动下一个线程之前,第一个代码Join到每个线程。

因此,所有线程都按顺序运行。

第二个代码立即运行所有线程,然后立即加入所有线程。

因此,线程在完全相同的数据上并发运行。

第二个代码可能无法工作,因为您的代码或数据不是线程安全的。

关于c# - 为什么线程连接在此示例中表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6375293/

相关文章:

c# - 向 System.Drawings.Color 添加颜色选项

c# - 在文本框中显示 ListView 的值

c# - 从 C# 调用 Python 方法(没有 IronPython)

c# - 停止线程

java - 在另一个同步方法中引用一个同步方法

c++ - 如何重载操作数 << 以像 ostream 样式一样使用

python-2.7 - 如何在 pandas DataFrame 中选择性地乘法或添加列?

sql - Linq lambda 表达式 (GROUP_CONCAT/STRING_AGG) 中 XML PATH 和 Stuff 的等价物是什么?

c# - Entity Framework Lambda 优化

c# - 如何使用 C# 使用 XPath 返回元素值?