多线程程序中boostweak_ptr实现资源池

Boost weak_ptr#39;s in a multi-threaded program to implement a resource pool(多线程程序中boostweak_ptr实现资源池)

本文介绍了多线程程序中boostweak_ptr实现资源池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑使用 boost::weak_ptr 来实现一个对象池,这样当没有人使用其中一个对象时,它们就会被回收.不过,我担心的是,它是一个多线程环境,似乎在最后一个 shared_ptr 到超出范围的对象与从 weak_ptr 构造的新 shared_ptr 之间存在竞争条件.通常,您会使用锁或其他东西来保护此类操作;然而,这里的重点是您不知道 shared_ptr 何时可能超出范围.

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.

我对 boost::shared_ptr 和 boost::weak_ptr 有什么误解吗?如果没有,有人有什么好的建议吗?

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

谢谢.

安德鲁

推荐答案

要使用 weak_ptr,您通常必须通过用它构造一个 shared_ptr 来获取强引用.最后一步是原子性的:要么得到一个强引用,要么抛出一个 bad_weak_ptr 异常.(或者,在 weak_ptr 上调用 lock(),并获得强引用或 null.)

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.)

示例(使用lock();很容易适应其他风格):

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
    }
}

这篇关于多线程程序中boostweak_ptr实现资源池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:多线程程序中boostweak_ptr实现资源池

基础教程推荐