What would be the most elegant way to implement a Win32 equivalent of WaitForMultipleObjects in Java (v6). A thread is sleeping until one of several events occur. When that happens, I want to process it and get back to sleep. No data is required, just an event.
A:
Just guessing Object.wait(), Object.notify() and Object.notifyAll() would be enough.
Artyom Sokolov
2009-04-25 12:55:27
No, Object.wait() just waits for a single object. Typically when you use WaitForMultipleObjects() in Win32 you are waiting for one of several things to happen. When the wait returns it will give you the index of the object that caused it to release. Very handy if you have a single thread that waits for several clients.I have no good solution here but what I have done a few times to have the multiple collection point waiting for objects on a queue and then have a thread per object to wait for.When the single object waiters gets notified they put something on a queue and waits for instructions.
Fredrik
2009-04-25 22:50:25
Having said that, it is not a very good pattern so I wouldn't copy it :-). It was meant more as an example to describe the feature to Antyom.
Fredrik
2009-04-25 22:51:37
+3
A:
It really depends what you want to do with it, but you could do something as simple as using the wait/notify methods or you could use the structures in the java.util.concurrency package. The latter would personally be my choice. You could easily set up a BlockingQueue that you could have producers drop event objects into and consumers blocking on removing the events.
// somewhere out there
public enum Events {
TERMINATE, DO_SOMETHING, BAKE_SOMETHING
}
// inside consumer
Events e;
while( (e = queue.take()) != TERMINATE ) {
switch(e) {
case DO_SOMETHING:
// blah blah
}
}
// somewhere else in another thread
Events e = BAKE_SOMETHING;
if( queue.offer(e) )
// the queue gladly accepted our BAKE_SOMETHING event!
else
// oops! we could block with put() if we want...
Jason Coco
2009-04-25 12:56:31
I want to have a simplest construction without any additional objects. Here's the pseudo code :int event;while ( (event = waitOnSomething()) != termination){ switch(event){ case 0: // do stuff case 1: // do stuff }}
Dima
2009-04-25 13:21:35
You can use an enum as your event (so you can switch on them and everything) and just use a basic blocking queue in that case. Your consumer thread will block on queue.take() -- that will block until somebody throws something in the queue with queue.offer() or something similar.
Jason Coco
2009-04-25 13:37:35