|
-
Apr 23rd, 2011, 05:09 PM
#1
Thread Starter
Frenzied Member
Queue with worker threads
Hi,
I have a bunch of objects that need processing by a script.
What I'm doing now is the following:
- Storing them in a queue
- Letting the worker threads process them when they're available.
I'm doing that by dequeueing from a synchronized instance of the queue.
To quote the documentation:
To guarantee the thread safety of the Queue, all operations must be done through the wrapper returned by the Synchronized method.
But as I was afraid, it sometimes dequeues the same object twice.
So, questions:
1. Is myQueue.Dequeue() safe for usage without synchronization?
2. If not, is this the following the correct fix for my problem?
3. (if you have time) Could anyone explain to me what the lock() actually does?
Does it pause all other threads hitting the same block until that block is finished?
Code:
lock (this._instanceLock)
{
entity = this._eventQueue.Dequeue();
}
As always, thanks for any input
Delete it. They just clutter threads anyway.
-
Apr 25th, 2011, 05:21 AM
#2
Re: Queue with worker threads
Don't use a a Queue at all. Just use the ThreadPool. Call QueueUserWorkItem and pass the object to be processed.
-
Apr 25th, 2011, 05:27 AM
#3
Thread Starter
Frenzied Member
Re: Queue with worker threads
Yes, I used the ThreadPool earlier, but there is a certain event that requires all threads to abort.
Because the script is dynamic and can contain thread sleeping having a 'cancel'-flag is not an option here.
Anyway, the snippet I posted earlier seems to do the trick, but is it actually correct usage there?
Delete it. They just clutter threads anyway.
-
Apr 25th, 2011, 05:46 AM
#4
Re: Queue with worker threads
If you want a thread-safe Queue then you would do like this:
csharp Code:
Queue q = Queue.Synchronized(new Queue());
and then enqueue and dequeue using 'q'. If you're going to use a 'lock' statement then you may as well use a generic Queue, which doesn't support synchronisation inherently.
-
Apr 28th, 2011, 01:50 AM
#5
Re: Queue with worker threads
Maybe I'm thinking of Queue<T> but I was pretty sure that Enqueue and Dequeue methods were safe to call from multiple threads without needing to synchronise.
-
Apr 28th, 2011, 02:01 AM
#6
Re: Queue with worker threads
 Originally Posted by Evil_Giraffe
Maybe I'm thinking of Queue<T> but I was pretty sure that Enqueue and Dequeue methods were safe to call from multiple threads without needing to synchronise.
As with most collections, the generic Queue is less functional that its non-generic counterpart in this regard.
 Originally Posted by MSDN
To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|