线程启动时的竞态条件? [英] Race condition during thread start?

查看:144
本文介绍了线程启动时的竞态条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行下面的代码来启动我的线程,但它们不按预期启动。出于某种原因,某些线程以相同的对象开始(有些甚至不启动)。如果我尝试进行调试,它们就会启动得很好(单击F10逐步添加代码就会增加额外延迟)。
$ b

这些是我的表单应用程序中的函数:

  private void startWorkerThreads()
{
int numThreads = config.getAllItems()。Count;
int i = 0;

foreach(config.getAllItems()中的ConfigurationItem tmpItem)
{
i ++;
var t = new Thread(()=> WorkerThread(tmpItem,i));
t.Start();
// return t;



private void WorkerThread(ConfigurationItem cfgItem,int mul)
{
for(int i = 0; i <100; i ++ )
{
Thread.Sleep(10 * mul); $(){
}
this.Invoke((ThreadStart)delegate()
{
this.textBox1.Text + =Thread+ cfgItem.name +Complete!\r\\ \\ n;
this.textBox1.SelectionStart = textBox1.Text.Length;
this.textBox1.ScrollToCaret();
});
}

任何人都可以帮助我?
<解决方案

解决方案

你提供了<$ c($ c

)直接从foreach循环获取$ c> ConfigurationItem 。这导致了这样一个事实,即所有的线程都会得到相同的项目(最后一个)。



为了让这个工作起作用,您必须为每个项目创建一个参考,将这个应用到每个线程:

$ foreach(config.getAllItems()中的ConfigurationItem tmpItem)
{
我++;
var currentI = i;
var currentItem = tmpItem;
var t = new Thread(()=> WorkerThread(currentItem,currentI));
t.Start();
// return t;
}

您还应该考虑使用ThreadPool。




I'm running the following code to start my threads, but they don't start as intended. For some reason, some of the threads start with the same objects (and some don't even start). If I try to debug, they start just fine (extra delay added by me clicking F10 to step through the code).

These are the functions in my forms app:

private void startWorkerThreads()
{
    int numThreads = config.getAllItems().Count;
    int i = 0;

    foreach (ConfigurationItem tmpItem in config.getAllItems())
    {
        i++;
        var t = new Thread(() => WorkerThread(tmpItem, i));
        t.Start();
        //return t;
    }
}

private void WorkerThread(ConfigurationItem cfgItem, int mul) 
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(10*mul);
    }
    this.Invoke((ThreadStart)delegate()
    {
        this.textBox1.Text += "Thread " + cfgItem.name + " Complete!\r\n";
        this.textBox1.SelectionStart = textBox1.Text.Length;
        this.textBox1.ScrollToCaret();
    });
}

Anyone able to help me out?

解决方案

You just run into the (be me called) lambda error.

You provide the ConfigurationItem from the foreach loop directly. This leads to the fact, that all your threads get the same item (the last one).

To get this to work you have to create a reference for each item and apply this to each thread:

foreach (ConfigurationItem tmpItem in config.getAllItems())
{
        i++;
        var currentI = i;
        var currentItem = tmpItem;
        var t = new Thread(() => WorkerThread(currentItem, currentI));
        t.Start();
        //return t;
}

And you should also consider using a ThreadPool.

这篇关于线程启动时的竞态条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆