Can two threads safely work on a linked list without locking?
Hey,
I have a linked list that two threads work on simultainiousley. The first thread is adding elements to end the linked list while the second is removing them from the front. Can this be done without a lock on the linked list head when elements are being added/removed? I think this lock is causing a performance hit to my application. If there isnt any safe way without it then thats fine but just thought I would check. The first thread uses this fuction to add elements to the list. Full source here. http://opennop.svn.sourceforge.net/v...h?&view=markup Code:
/* Lets add the new packet to the queue. */ Code:
pthread_cond_signal(&workers[queuenum].signal); Code:
/* Lets get the next packet from the queue. */ |
Quote:
One primitive way of telling if it is would be to use pthread_mutex_trylock() instead of the blocking ..._lock() call, put it in a simple loop, and see how many times you have to trylock() before you get it. If it's not very often, look elsewhere. Or, of course, you could use a profiler... |
Before spending too much time on the performance question, it might be good to focus on the original question: is it safe? Well, no. No, it isn't.
Even the act of incrementing or decrementing the number of items in the list isn't safe without a lock. |
That's what I though but wanted to make sure. There might be some improvement by changing the order of those two lines so a sleeping thread is not woken up while there is still a lock on the queue. The would only help if the thread were sleeping.
|
Quote:
But what you do inside the respective locks might be optimized/reduced. From the excerpts you posted,
So, not knowing the rest of your code, the following (untested!) code might be slighly more efficient: Code:
/* add packet to the queue. */ |
Thanks for the ideas. Your right I don’t really care about the qlen or being able to traverse the list in reverse order so removing that might allow me to decrease the time the thread holds the lock. That part that probably takes the longest is incrementing/decrementing the qlen counter too so by removing that it might improve the speed quite a bit.
|
Quote:
Use a profiler or some other method to see if there's actually a bottleneck where you think there is. Otherwise, you'll just be using up your precious time to deliberately obfuscate your code, and that would just be silly-silly-silly. |
A more whimsical approach would be these optimization rules:
|
Quote:
Having said that, back to the original question: Yes, there is a (somewhat ugly) way to work on a linked list without locking. Does it make sense? Probably not. But it can be done. Well, not completely without locking. The writer still has to acquire the mutex for every change, but the reader can safely remove packets from the queue without locking, if
Quote:
But I would strongly recommend against doing that as
|
All times are GMT -5. The time now is 08:06 AM. |