多个线程更新阵列 [英] Multiple threads updating array

查看:93
本文介绍了多个线程更新阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着去实现多线程在我的应用程序,使得大量浮点数计算(神经网络)。

Im trying to implement multi-threading in my application that makes a lot of float number calculations (neural network).

我写的功能,使必要的计算和更新阵列功能之外。 我的实际,单线程code看起来像这样(简化为更好地理解):

I wrote function that makes necessary calculations and updates array outside that function. My actual, single-thread code looks like this (simplified for better understanding):

class MyClass
{
    // this array after all calculations should contain 
    // result of only one calculation, 
    // that returned smallest value in one of array fields 
    // (smallest neural network error)
    float[] bestResult;

    // runs calculations on all "sets of data"
    public void findBestResult(void)
    {
        foreach (something...) // data rows from database cached in one array
        {
            calculate(x[]);
        }
    }

    // calculates one "set of data"
    public void calculateAndUpdateResultIfBetter(float[] inputData)
    {

        if (bestResult[0] > calculatedData[0])
             bestResult = calculatedData; // update only if condition is true
    }

}

林较低水平的程序员,我不知道如何使用先进的(?).NET线程技术,使用同步等我知道如何创建的东西,一个额外的线程,并通过使用委托更新的形式某些控件。

Im low level programmer, i don't know how to use advanced (?) .NET threading techniques, that use Synchronize etc. I know how to create one additional thread for something and update some controls on form by using delegates.

我不知道如何与2-8线做的正是同样的事情,互相竞争的工作。

I have no idea how to work with 2-8 threads doing exactly same thing and competing with each other.

问题1 - 你能帮助我吗?我不知道如何下手。解决的尼科德拉斯科维奇

The question 1 is - can you help me with this? I don't know how to start. SOLVED BY Niko Drašković

编辑: 问题2 - 将锁定()方法锁住我的阵列的读取和写入

The question 2 is - will lock() method lock my array for read and write?

推荐答案

您使用锁定语句prevent不同的线程运行相同的code与此同时。就需要一个参考作为标识符的锁使用。它的共同创建简单对象,仅用于该锁定

You use the lock statement to prevent different threads to run the same code at the same time. You would need a reference to use as an identifier for the lock. It's common to create a simple object that is used only for the locking:

float[] bestResult;
object sync = new Object();

然后围绕code访问您使用数组锁定

lock (sync) {
  if (bestResult[0] > calculatedData[0]) {
    bestResult = calculatedData;
  }
}

您可能希望有每个线程首先计算,它可以说是负责数据中看到,然后再结合这些最佳值的最佳值。如果运行锁定code往往你会做的线程彼此等待,失去了很多的理由摆在首位运行单独的线程。

You might want to have each thread first calculate the best value that it can see within the data that it is responsible for, and then combine those best values. If you run the locked code too often you will make the threads wait for each other, losing a lot of the reason for running separate threads in the first place.

这篇关于多个线程更新阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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