简体   繁体   English

多线程中的循环界限

[英]For loop bounds in Multi Threading

I have a main thread that makes some other threads in two nested for. 我有一个主线程,使其他两个线程嵌套在一起。

private void mainthread()
        {
            List<Thread> ts= new List<Thread>();

            for (int w=0; w<7; w+=2)
                for (int h = 0; h < 5; h+=3)
                {
                    Thread t = new Thread(delegate() { otherthreads(w, h); });
                    ts.Add(t);
                    t.Start();
                }
            for (int i = 0; i < ts.Count; i++)
                ts[i].Join();
        }

        private void otherthreads(int w, int h)
        {                    
            listBox1.Invoke(new singleparam(addtolistbox), new object[] { "w:" + w.ToString() + ",h:" + h.ToString() });        
        }

Each thread adds it's input arguments to a Listbox. 每个线程将其输入参数添加到列表框。 I am confused why the input arguments of some threads are not in the for bounds? 我很困惑为什么某些线程的输入参数不在范围内?

在此处输入图片说明

Your loop is running correctly, but what is happening is this: the delegate knows that it must pass w and h onto the otherthreads() function, but those values are not bound until it is actually invoked. 您的循环正确运行,但是发生的是这样:委托知道它必须将wh传递给otherthreads()函数,但是这些直到被实际调用时才被绑定。 In other words, prior to the delegate actually executing, it just knows it must use w and h . 换句话说,在委托实际执行之前,它只知道必须使用wh On your last iteration, you are asking for the delegate to execute, but before it can, w and h increment for the final time on the initiating thread, causing their values to be 8 and 6, respectively. 在最后一次迭代中,您正在要求委托执行,但在此之前, wh在启动线程的最后时间递增,导致它们的值分别为8和6。 The loops exit. 循环退出。 Then, picomoments later, the delegate executes and NOW has the values of w and h ... but the values are now 8 and 6. 然后,在随后的时刻,委托执行并现在具有wh ...的值,但现在的值为8和6。

You can avoid this by "snapshotting" w and h with local variables to the tightest scope around the delegate and assigning their values appropriately: 您可以通过使用局部变量“快照” wh到委托周围最紧密的范围并适当分配其值来避免这种情况:

for (int h = 0; h < 5; h+=3) 
{
    int h2=h;
    int w2=w;

    Thread t = new Thread(delegate() { otherthreads(w2, h2); });
    ts.Add(t);
    t.Start();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM