If another thread is reading from the queue then wait till that thread is done. Do not block if a thread is writing into the queue
If another thread is writing to the queue, wait till that thread is done. Do not block if a thread is reading from the queue
Tushar Goel wrote:For an example: I have 3 read thread and 3 write thread, Say if 1 read thread acquire lock and found queue is empty so it goes to while loop
and if same time other read threads come then they have to wait as lock is already been acquired by other read thread.
Same is for write thread. First thread acquire lock and check if queue is full or not. If full then wait for queue to make a space. If in meantime
other write threads come then they will wait for acquire lock.
Unless it's a busy wait, which is a horrible solution
Then you need a third lock to synchronize the buffer pointers on. This is a shared lock between *all* the threads, which has 2 conditions that can be awaited.
Tushar Goel wrote:Here i am starting a thread each time an object is inserted or removed. I think it is not correct..
Checking whether the queue has an item is part of the read operation, so this should be part of the critical section. No two readers may check the queue at the same time,
because if one element is available, two readers may pass the check before one of them reads and discards the element.
The second mistake is that you're not releasing lock correctly. If an exception occurs in the first while loop, then lock is never released, and the program deadlocks. Locks should *always* be used like this:
Finally, since the lock spans the entire run() method, readers and writers can't access the queue at the same time. You should only lock the shared lock when you're performing checks.
A
B
[D, null, C]
Mike, the happens-before relationship is established by lock.lock(). Readers and writers share the same lock. The problem in this case is that the lock spans the entire method call, so both the readers and writers have mutually exclusive access, which is not what the assignment requires.
This won't work. What happens if there is one space left in the buffer and two add operations happen at the same time? They both pass the check, and then one attains the permit. It fills the empty space, releases the permit, and then the second add operation overwrites an occupied space.
Tushar Goel wrote:One more doubt when i am trying to add suppress warning annotation at line 9 in code as below it gives my compilation problem.
Won't you be my neighbor? - Fred Rogers. tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
|