.net中的线程安全队列(列表)
我需要创建一个线程安全的项目列表以添加到 lucene 索引中。
下面的线程安全吗?
public sealed class IndexQueue
{
static readonly IndexQueue instance = new IndexQueue();
private List<string> items = new List<string>();
private IndexQueue() { }
public static IndexQueue Instance {
get { return instance; }
}
private object padlock = new object();
public void AddItem(string item) {
lock (padlock) {
items.Add(item);
}
}
}
即使从内部列表中获取项目也需要锁定吗?
我们的想法是,我们将运行一个单独的任务来从索引队列中获取项目并将它们添加到 lucene 索引中。
谢谢 本
I need to create a thread safe list of items to be added to a lucene index.
Is the following thread safe?
public sealed class IndexQueue
{
static readonly IndexQueue instance = new IndexQueue();
private List<string> items = new List<string>();
private IndexQueue() { }
public static IndexQueue Instance {
get { return instance; }
}
private object padlock = new object();
public void AddItem(string item) {
lock (padlock) {
items.Add(item);
}
}
}
Is it necessary to lock even when getting items from the internal list?
The idea is that we will then have a separate task running to grab the items from indexqueue and add them to the lucene index.
Thanks
Ben
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的实现似乎是线程安全的,尽管您在从
items
读取时也需要锁定 - 如果存在并发Add操作。如果您进行枚举,则还需要对其进行锁定,并且该锁定需要与枚举器一样长。
如果您可以使用 .net 4,我强烈建议您查看 System.Collections.Concurrent 命名空间。它有一些经过良好测试且性能相当好的集合,这些集合是线程安全的,并且实际上针对多线程访问进行了优化。
Your implementation seems thread-safe, although you will need to lock when reading from
items
as well - you can not safely read if there is a concurrentAdd
operation. If you ever enumerate, you will need locking around that as well and that will need to live as long as the enumerator.If you can use .net 4, I'd strongly suggest looking at the System.Collections.Concurrent namespace. It has some well tested and pretty performant collections that are thread-safe and in fact optimized around multiple-thread access.
当您进行修改时,List 类不是线程安全的。在以下情况下有必要锁定:
想必第一个是正确的,否则你就不会问这个问题。第二个显然是正确的,因为
Add
方法修改了列表。所以,是的,你需要它。当您向类添加一个允许您读回项目的方法时,也需要锁定,重要的是您必须使用与
AddItem
。The List class is not thread-safe when you make modifications. It's necessary to lock if:
Presumably the first is true otherwise you wouldn't be asking the question. The second is clearly true because the
Add
method modifies the list. So, yes, you need it.When you add a method to your class that allows you to read back the items it is also necessary to lock, and importantly you must use the same lock object as you did in
AddItem
.是的;虽然检索本质上并不是不安全的操作,但如果您还向列表写入数据,那么您就会面临在写入过程中进行检索的风险。
如果它像传统队列一样运行,则尤其如此,其中检索实际上会从列表中删除检索到的值。
Yes; while retrieval is not an intrinsically unsafe operation, if you're also writing to the list, then you run the risk of retrieving in the middle of a write.
This is especially true if this will operate like a traditional queue, where a retrieval will actually remove the retrieved value from the list.