Boost logo

Boost :

From: Sergey Skorniakov (s.skorniakov_at_[hidden])
Date: 2007-11-12 05:06:09


I had very surprised that boost::function became not thread-safe in 1.34 and this remains in 1.34.1 But boost::thread uses boost::function as argument in its constructor and situation became ridiculous - code that look like this:

void foo() {}

void bar()
{
    boost::thread x(&foo);
}

is no longer thread-safe. I had found a short discussion about function thread-safety, but what I should write instead of sample above? Do I need to have a global mutex and protect construction of boost::function before passing it in thread, if I want to call bar() from different threads?

void foo() {}
void bar()
{
    boost::function0<void> f;
    {
        mutex::scoped_lock lock(my_global_mutex_for_constructing_function_from_foo);
        f = &foo;
    }
    boost::thread x(f);
}

I think that something needs to be changed:
1) function should be thread-safe (more preferable for me, but may be inconvenient for someone else)
2) or thread should not use boost::function
3) or unsafe function constructor should be explicit (to prevent first sample from compiling) and fact that it is unsafe should be mentioned in the documentation.
4) or two version of boost::function - thread-safe and unsafe should be present in library, and boost::thread should use safe version.


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