gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:40:45 25 4
gpt4 key购买 nike

更新的问题更加通用:

我有以下代码。当交换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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com