Boost logo

Boost :

From: Andrey Melnikov (melnikov_at_[hidden])
Date: 2005-08-17 23:12:47


Oliver Kullmann wrote:

> Given two functions
>
> bool f1(X x);
> bool f2(X x);
>
> I want to compute the logical or (short-circuit!).
>
> Now boost::thread did not support thread cancellation or termination
> in version 1_32, and it seems that development of boost::thread has
> been cancelled itself.
> To cancel a thread is essential to gain the speed-up possible
> by the parallel short-circuit evaluation, and thus
> boost::thread seems not to be usable.
>
> Now how are you proceeding? In the FAQ's of boost::thread one can read
>
> ----
>
> 9. Why isn't thread cancellation or termination provided?
>
> There's a valid need for thread termination, so at some point
> probably will include it, but only after we can find a truly safe
> (and portable) mechanism for this concept.
>
> ----
>
> How do you cancel threads?

The explanation in the FAQ doesn't explain the problem in details.
Here's a brief example:

bool f1(X x)
{
        X * y = new X;
        // if f1() is aborted at this point
         // *y won't be deallocated
        delete y;
        return false;
}

> Can one compute the short-circuit parallel or with your "futures" ?!

This is a common problem in the world of parallel computations. It's due
to the nature of parallel exectution and it's independent from
boost::thread, futures or any library.

Basically, the solution is always the same: f1() polls a flag
periodically, and if it is raised it exits.

To cancel the thread you just raise the flag and the thread terminates
itself:

class A
{
     Flag cancel_f1;
     bool f1(X x)
     {
         X * y = new X;
        for (int i = 1; i < 1000; i++)
         {
             // some computations, e.g. one iteration of the algorithm
             if (flag.is_raised())
             {
                  delete y;
                   return false;
             }
         }
        return actual_result;
     }
}

...
A a;
a.run_f1_in_a_new_thread();
a.cancel_f1.raise();

> 3) How is access to common storage handled with you approach?!
> (I would appreciate a short explanation using not too much jargon
> --- yet I have only written one multi-threaded program (and that to explore
> the boost::thread library).)

It isn't handled at all. You should use boost::thread synchronization
primitives to handle it properly when you implement f1().

Andrey


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk