Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

c++ - Boost weak_ptr's in a multi-threaded program to implement a resource pool

I'm thinking of using boost::weak_ptr to implement a pool of objects such that they will get reaped when nobody is using one of the objects. My concern, though, is that it's a multi-threaded environment, and it seems there's a race condition between the last shared_ptr to an object going out of scope and a new shared_ptr being constructed from the weak_ptr. Normally, you'd protect such operations with lock or something; however, the whole point here is that you don't know when the shared_ptr might be going out of scope.

Am I misunderstanding something about boost::shared_ptr and boost::weak_ptr? If not, does anybody have any good suggestions on what to do?

Thanks.

Andrew

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To use a weak_ptr, you normally have to grab a strong reference by constructing a shared_ptr with it. This last step is atomic: you either get a strong reference back, or you get a bad_weak_ptr exception thrown. (Alternatively, call lock() on the weak_ptr, and either get a strong reference or null.)

Example (with lock(); easy enough to adapt to the other style):

void do_something(weak_ptr<foo> weak) {
    // Grab strong reference
    shared_ptr<foo> strong(weak.lock());
    if (strong) {
        // We now have a strong reference to use
    } else {
        // No strong references left; object already freed
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...