实现“线程安全”链表
我正在编写一个应用程序,其中多个链接列表在线程之间共享。对链表的操作如常:查找、插入、删除、修改节点内容。 我遇到了一个实现来保持链接列表操作的整个过程“线程安全”。 http://www.cs.cf.ac.uk/Dave /C/node31.html#SECTION003100000000000000000
但想知道我是否可以按如下方式进行操作:
lock(mutex)
link list operation
unlock(mutex)
即,我将互斥锁与每个链接列表相关联,并在每次开始操作时都按上面的方式使用它,
将不胜感激
I am writing an applicaation where more then one link list is shared among threads. Operations on the linked list is as usual:searching,inserting,deleting,modifying node contents.
I came across ann implementation to keep the entire procedure of link list operation "thread-safe". http://www.cs.cf.ac.uk/Dave/C/node31.html#SECTION003100000000000000000
But was wondering if I caan do it as follows:
lock(mutex)
link list operation
unlock(mutex)
I.e I associate a mutex with each link list and use it as above whenever I start an operation
Would be gratefull for views
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以通过这种方式做到这一点,但是您会牺牲活性,因为链接列表现在一次只能被一个线程接触 - 这可能会导致列表成为程序中的瓶颈。
考虑一下链表的接口(线程可以调用哪些方法)以及如何保持链表安全,同时允许尽可能多的线程同时使用它。
例如,如果您将列表用作队列,则一个线程可能会将列表尾部的项目入队,而另一个线程则将项目出队。
创建线程安全实用程序面临很多挑战,但您应该尽可能采取外科手术,以确保您不会牺牲首先通过并行化软件获得的性能!玩得开心!
It is possible to do it this way, but you sacrifice liveness as the linked list can now only be touched by one thread at a time - this may lead to the list becoming a bottleneck in your program.
Think about the interface of the linked list (what methods may be called by the threads) and how you can keep the list safe, but also allow as many threads as possible to use it at once.
For example, if you're using the list as a queue, one thread could be enqueueing items at the tail of the list, while another thread dequeues an item.
There are lots of challenges in creating thread safe utilities, but you should try to be as surgical as possible to make sure you aren't sacrificing the performance that you're trying to gain by parallelising your software in the first place! Have fun!
视情况而定。如果您的线程主要搜索列表而不修改它们,那么实现读取器/写入器锁可能是值得的。只要其他线程没有修改该信息,就没有理由阻止其他线程读取该信息。然而,如果最常见的操作涉及修改列表或其中的信息,则可能不会有太多收获,因此简单的锁定/执行操作/解锁方案应该同样有效。
Depends. If your threads will mainly search through the lists without modifying them, it may be worthwhile to implement a reader/writer-lock. There's no reason to prevent other threads from reading the information as long as none of them modifies it. If however, the most common operations involve modifying the lists or the information in them, there may not be much to gain, so a simple lock/do operation/unlock scheme should work just as well.