开发者

Implementing 'thread-safe" linked list

开发者 https://www.devze.com 2023-03-12 10:01 出处:网络
I am writing an applicaation where more then one link list is shared among threads. Operations on the linked list is as usual:search开发者_开发百科ing,inserting,deleting,modifying node contents.

I am writing an applicaation where more then one link list is shared among threads. Operations on the linked list is as usual:search开发者_开发百科ing,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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号