Boost logo

Boost :

From: Roland Schwarz (roland.schwarz_at_[hidden])
Date: 2006-10-04 13:03:50


Felipe Magno de Almeida wrote:
> The problem is that it isnt possible when a ptr must be used in a free
> template function and the pointer is parameterized on the template
> function parameters. That was the spirit case. There isnt any solution
> from the boost.thread for this. Which, IMO, it leads to believe that
> thread_specific_ptr is the solution. After all, it is the only public
> solution for tss in boost.thread.

I did a liitle further research on the problem.
In the function

void foo()
{
        static testclass bar;
}

the constructor call must be somehow conditioned on
a variable (which normally is invisible to user code
and automaticall compiler generated).

This variable _is_ a shared resource and as such _must_
be protected!

So if we had a statically initializeable mutex, we would
say:

void foo()
{
        static mutex mtx = STATIC_MUTEX_INITIALIZER;
        scoped_lock lk(mtx);
        
        static testclass bar;

        lk.unlock();
}

Since there is no static_mutex in the boost thread lib yet,
one might use either boost/regex/pending/static_mutex.hpp

or the following, which only uses boost::thread :

namespace {
     void dont_clean(boost::mutex**) {
     };
     boost::thread_specific_ptr<boost::mutex*> mutex_ptr(dont_clean);
     void mutex_init()
     {
         boost::mutex* pm = new boost::mutex;
         *(mutex_ptr.get()) = pm;
     }
}

void foo()
{
     static boost::mutex* bar_mutex = 0;
     static boost::once_flag bar_once = BOOST_ONCE_INIT;
     mutex_ptr.reset(&bar_mutex);
     boost::call_once(&mutex_init, bar_once);
     boost::mutex::scoped_lock bar_lock(*bar_mutex);

     static testclass bar;

     bar_lock.unlock();

     .... other code
}

There is a trade of currently between the both solutions:
When the regex solution falls back to boost::thread based
implementation there is only one global mutex beeing used
for all objects of static_mutex. This is not the case with
my solution. However mine leaves back a small memory leak
for each.

I definitely think boost thread should provide a static
initializeable mutex, and this already is on the todo list.
Altough the cleanup first has to be fixed.

After all I think, spirit should implement one of the
above in grammar.ipp, since both fix the outstanding bug.

Roland


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