c# - 这种使用静态队列线程安全吗?

标签 c# .net thread-safety

msdn 文档声明静态通用队列是线程安全的。这是否意味着以下代码是线程安全的?也就是说,一个线程Enqueues一个int,另一个线程同时Dequeues一个int,是不是有问题?为了线程安全,我是否必须锁定入队和出队操作?

class Test {
    public static Queue<int> queue = new Queue<int>(10000);

    Thread putIntThread;
    Thread takeIntThread;

    public Test() {
        for(int i = 0; i < 5000; ++i) {
            queue.Enqueue(0);
        }
        putIntThread = new Thread(this.PutInt);
        takeIntThread = new Thread(this.TakeInt);
        putIntThread.Start();
        takeIntThread.Start();
    }

    void PutInt() {
        while(true)
        {
            if(queue.Count < 10000) {//no need to lock here as only itself can change this condition
                queue.Enqueue(0);
            }
        }
    }

    void TakeInt() {
        while(true) {
            if(queue.Count > 0) {//no need to lock here as only itself can change this condition
                queue.Dequeue();
            }
        }
    }

}

编辑:我必须使用 .NET 3.5

最佳答案

这绝对不是线程安全的。来自 Queue<T> 的文档.

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

A Queue<T> can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

重读你的问题,你似乎对“这种类型的静态成员”这个短语感到困惑 - 它不是在谈论“静态队列”,因为没有这样的东西。对象不是静态的或不是静态的 - 成员是。当它谈论静态成员时,它谈论的是像 Encoding.GetEncoding 这样的事情。 (Queue<T> 实际上没有任何静态成员)。实例成员类似于 EnqueueDequeue - 与类型实例相关而不是类型本身的成员。

因此,要么您需要为每个操作使用锁,要么如果您使用的是 .NET 4,请使用 ConcurrentQueue<T> .

关于c# - 这种使用静态队列线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3870713/

相关文章:

.net - OpenTK 的 Vector2.Length 是 Vector2.LengthFast 的两倍

c# - 通过引用传递和使用 ref

java - 为什么我的应用程序有时会返回错误的输出?

java - 这个Java加密代码线程安全吗?

c# - 如何使用子泛型接口(interface)实现泛型接口(interface)

c# - 使用 C# 实现 Rabin-Karp 算法以在 LeetCode 28 "implement strStr()"中搜索字符串的问题

c# - 没有 add in linq 语法的定义?

c# - 在 F# 中创建本地函数

c# - 支持移除项的线程安全集合

c# - App.config 中的配置未正确提取