Sign in to follow this  
Harry Hunt

Waiting for another thread

Recommended Posts

Harry Hunt    542
Hi! I have written a little framework that implements the active object pattern and so far it's working great. In case you're not familiar with the pattern: it basically provides an easy mechanism for executing functions or methods asynchronously. Now in case you execute a function that returns a value, you receive a special object called a "Future" that gives you the function's return value once it has become available. It is also possible to explicitly wait for the return value like so:
int myFunction(int myArg) {
  return myArg + 5;
}

// Somwhere else
Future<int> myFuture = Future<int>::Spawn<int>(&myFunction, 32);
myFuture.Wait();
std::cout << "The result is " << myFuture.GetValue() << std::endl;

Now what Wait does is it blocks the thread it is called from until a return value is available. The Future is signalled by the thread that executes the function through a simple boolean variable that is set to "true" once the execution is done. Right now, Wait is implemented like this (I removed the code that deals with timeouts): bool Future<T>::Wait(int timeout) { while (!complete) ; // complete is a member of Future return true; } This works quite well, but I'm worried that the while-loop may actually consume a lot of resources, so I was wondering if there's a better way. Note that all the code so far is lock-free (as in no mutexes, no semaphores) and I'd really like to keep it that way. Any ideas?

Share this post


Link to post
Share on other sites
the_edd    2109
Yeah, you need to use a condition variable. Repeatedly checking a flag isn't guaranteed to work at all, and also needlessly hammers the processor as you say.

A full future implementation can be found here (there's a link in the boost cookbook recipe, too). There's support for propagating exceptions, passing and returning references and a bunch of other things you might be interested in.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this