Using threads to obtain a value

Z

Zachary P. Landau

I have a few classes that all try to obtain the same data as each
other using different methods. Each one takes around 5 seconds to get
the data, so I'd much rather have them all try to get it at once. I
only need the data once, from whoever gets it first.

So what I would like to do is have, lets say, fetchdata() for each
class called in a thread, and as soon as the first non-nil is returned
from fetchdata, I want to kill the other threads and go on with the
program.

I have read the threading documentation and tried to play around a bit
with it, but I can't seem to get it to do what I want. If someone
could tell me how to do it or give me a point in the right direction,
that'd be helpful.
 
R

Robert Klemme

My first approach would be this: Create a condition variable and a mutex,
start all threads giving them the condition var and mutex, wait on the
condition var in the main thread. In all threads if the value is
retrieved signal the condition var. In the main thread kill all non
terminated threads (or simply let them run) and proceed.

robert
 
Z

Zachary P. Landau

Kurt M. Dresner said:
If the computation is just raw computation, I don't think you're going
to see very much of a speedup by doing them in parallel. If they are
blocking for I/O or something like that at all, then there would be an
improvement, but otherwise not. Where is fetchdata getting the
information from? A remote source?

Yeah, it is fetching the information from webpages. Most of the code
other than waiting for pages to load is simple regexps, so I figured
this would be the perfect use for threads.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,186
Latest member
vinaykumar_nevatia

Latest Threads

Top