Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There is a fundamental flaw in your logic.</p> <p>I assume you intend the method <code>Device.getAvailableDevice( devices )</code> to return a device that is actually available - or even the device that will be the first to become available. But you lock the device only after that call. That means that more than one thread may observe the device to be available, and subsequently try to lock it. As a result, threads are indeed waiting in queues to obtain the device, that was supposed to be 'available'. And as a consequence, you ask how you can find out how many are waiting, as you want that information to implement <code>Device.getAvailableDevice( devices )</code>, if not to find one that nobody is waiting for, then at least to find the one that will become available soon.</p> <p>What you should do instead, is create some sort of device manager, that holds two collections: available devices and devices in use. The manager should have two methods: <code>GetAvailableDevice</code> which return a device that was available and sets it to in-use, and <code>ReturnDevice</code> which makes a device available again (i.e. move it from the in-use devices collection to the available devices collection).</p> <p>Those two methods lock on the device manager, but not on individual devices. The <code>GetAvailableDevice</code> call is blocking, threads might be waiting for the manager to return one. The <code>ReturnDevice</code> call is not blocking, in the sense that it returns immediately.</p> <p>For more information on how to implement such a structure, I suggest you read "Threading in C#" by Joseph Albahari, see <a href="http://www.albahari.com/threading/" rel="nofollow">http://www.albahari.com/threading/</a>.</p> <p>A solution based on a queue per device needs to decide now what device will be busy or available in the future. And when it decides, the first thing that happens is that the thread that requested it starts waiting for that specific device (possibly for a zero period of time).</p> <p>A solution based on a single queue for all devices combined does not need to predict the future. As a device becomes available, any device, it gives it to a waiting thread that can immediately start to use it. Threads wait for the device manager to give them a device (possibly for a zero period of time), but not for the device that is given to them. This solution also avoids the situation where a thread is still waiting for a device, while another device has already become available, with no threads waiting for it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload