C# 数组线程安全吗? [英] Are C# arrays thread safe?

查看:28
本文介绍了C# 数组线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

特别是

  1. 创建一个函数以将数组和索引作为参数.
  2. 创建一个 n 元素数组.
  3. 创建一个 n 计数循环.
  4. 在新线程的循环内,使用传入的索引器将对象的新实例分配给数组.

我知道如何管理线程等.我很想知道这是否是线程安全的做某事的方式.

I know how to manage the threads etc. I am interested in know if this is thread safe way of doing something.

 class Program
{
    // bogus object
    class SomeObject
    {
        private int value1;
        private int value2;

        public SomeObject(int value1, int value2)
        {
            this.value1 = value1;
            this.value2 = value2;
        }
    }

    static void Main(string[] args)
    {

        var s = new SomeObject[10];
        var threads = Environment.ProcessorCount - 1;
        var stp = new SmartThreadPool(1000, threads, threads);
        for (var i = 0; i < 10; i++)
        {
            stp.QueueWorkItem(CreateElement, s, i);
        }

    }

    static void CreateElement(SomeObject[] s, int index)
    {
        s[index] = new SomeObject(index, 2);
    }
}

推荐答案

我相信如果每个线程只作用于数组的一个单独部分,一切都会好起来的.如果您要共享数据(即在线程之间进行通信),那么您将需要某种内存屏障来避免内存模型问题.

I believe that if each thread only works on a separate part of the array, all will be well. If you're going to share data (i. e. communicate it between threads) then you'll need some sort of memory barrier to avoid memory model issues.

相信,如果你产生一堆线程,每个线程填充它自己的数组部分,然后使用 Thread.Join,这在障碍方面足以让您安全.我目前没有任何支持文档,请注意...

I believe that if you spawn a bunch of threads, each of which populates its own section of the array, then wait for all of those threads to finish using Thread.Join, that that will do enough in terms of barriers for you to be safe. I don't have any supporting documentation for that at the moment, mind you ...

您的示例代码是安全的.任何时候都不会有两个线程访问同一个元素——就好像它们每个都有单独的变量一样.但是,这本身并没有什么用处.在某些时候,线程通常会想要共享状态——一个线程会想要读取另一个线程所写的内容.否则,他们写入共享数组而不是写入自己的私有变量是没有意义的.这就是需要注意的点 - 线程之间的协调.

Your sample code is safe. At no time are two threads accessing the same element - it's as if they each have separate variables. However, that doesn't tend to be useful on its own. At some point normally the threads will want to share state - one thread will want to read what another has written. Otherwise there's no point in them writing into a shared array instead of into their own private variables. That's the point at which you need to be careful - the coordination between threads.

这篇关于C# 数组线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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