threading

  • Thread starter Thread starter laimis
  • Start date Start date
L

laimis

Hey guys,

I am writing this one multithreaded app where I do synchronization
between producer/consumer with boolean flags and busy waiting. How much
more efficient is Monitor.Wait(syncobj) and Monitor.Signal(syncobj)
combinations?
 
laimis said:
I am writing this one multithreaded app where I do synchronization
between producer/consumer with boolean flags and busy waiting. How much
more efficient is Monitor.Wait(syncobj) and Monitor.Signal(syncobj)
combinations?

Much, much, much more efficient. (You probably need to use boolean
flags as well, but busy waiting is a really bad idea.)

See http://www.pobox.com/~skeet/csharp/threads/deadlocks.shtml for a
producer/consumer queue (it's about half way down).
 
Yeah, consumer/producer based on wait/pulse sounds nice. Here is my
concern and situation:

Let's say I have one buffer that two threads will share (instead of a
queue). One thread will place data into it, the other thread will read
data out of it. How to make sure that producer, after placing the data
in, doesn't acquire the lock faster than the consumer and overwrite the
already existing data in the buffer? It is not a problem in a queue
since nothing will be overwritten, just an extra queue item will be
enqueued.

Would it be a bad approach to introduce some flag that producer sets
when it finishes filling up buffer and doesn't attempt to fill the
buffer unless the flag is unset. Reader meanwhile reads the buffer once
it acquires the lock and unsets the flag once it is done reading to mark
the buffer ready to be filled.
 
laimis said:
Yeah, consumer/producer based on wait/pulse sounds nice. Here is my
concern and situation:

Let's say I have one buffer that two threads will share (instead of a
queue). One thread will place data into it, the other thread will read
data out of it. How to make sure that producer, after placing the data
in, doesn't acquire the lock faster than the consumer and overwrite the
already existing data in the buffer? It is not a problem in a queue
since nothing will be overwritten, just an extra queue item will be
enqueued.

Would it be a bad approach to introduce some flag that producer sets
when it finishes filling up buffer and doesn't attempt to fill the
buffer unless the flag is unset. Reader meanwhile reads the buffer once
it acquires the lock and unsets the flag once it is done reading to mark
the buffer ready to be filled.

If you're going to do that, you might want to think about having two
producer/consumer queues, one of which works each way - when the
consumer has consumed the data, it can "produce" an event saying "I'm
finished" which the consumer can consume.

I'd think about using different buffers for different work items though
- that would allow more parallelism. (You could always have a stock of
them, and reuse them when appropriate.)
 
Back
Top