|
Boost Users : |
From: Matthew Peltzer (goochrules_at_[hidden])
Date: 2005-08-17 17:03:56
On 8/17/05, Christopher Hunt <huntc_at_[hidden]> wrote:
> On 18/08/2005, at 1:19 AM, boost-users-request_at_[hidden] wrote:
>
> > I envisage two threads accessing a function like this concurrently:
> >
> > template<typename T>
> > boost::shared_ptr<T>
> > my_func()
> > {
> > static boost::mutex m;
> > boost::mutex::scoped_lock l(m);
> >
> > static boost::shared_ptr<T> p(new T);
> > return p;
> > }
> >
> > and my worry is that both threads could attempt to do the static
> > initialisation of m concurrently. Is there protection against this?
> > Is it even possible to protect against this?
>
> The scope of m is actually outside of your function given that it is
> static. Thus it will be initialised outside of your function generally
> before any other threads get to start up.
This does not sound right to me, so I whipped up a test case... on
HP-UX, given the code:
#include <iostream>
#include <string>
class C {
public:
C(const std::string& str) {
std::cout << "C::C(" << str << ")" << std::endl;
str_ = str;
}
~C() {
std::cout << "C::~C(" << str_ << ")" << std::endl;
}
private:
std::string str_;
};
C c("global");
void f() {
static C c("static");
}
int main(int argc, char* argv[]) {
C c("local");
f();
return 0;
}
the output will be:
> g++ -o static static.cpp
> ./static
C::C(global)
C::C(local)
C::C(static)
C::~C(local)
C::~C(static)
C::~C(global)
Given my experience, this is what I expected. The static instance is
not created until the function is called, and is destroyed just before
global instances are destroyed.
So, I would say that there is a race condition in the original code
with mutex m, if there could be two threads entering my_func() for the
first time.
-- Matthew Peltzer
-- goochrules_at_[hidden]
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net