使用指针对共享模型进行线程化
我有一个指向使用 new 创建的对象的指针向量。多个线程通过各种获取/设置以安全的方式访问该向量。然而,一个线程可能会删除其中一个对象,在这种情况下,另一个线程指向该对象的指针不再有效。方法如何知道指针是否有效?选项 1 和 2 实际上似乎效果很好。我不知道他们将如何扩展。最好的方法是什么?有便携版3吗?
测试有效的指针有效性示例:
1. 使用整数而不是指针。哈希 (std::map) 检查指针是否仍然有效。公共方法如下所示:
get(size_t iKey)
{
if((it = mMap.find(iKey)) != mMap.end())
{
TMyType * pMyType = it->second;
// do something with pMyType
}
}
2.有一个shared_ptr向量。每个线程都尝试在其weak_ptr上调用lock()。如果返回的shared_ptr为null,我们就知道有人在我们等待时删除了它。公共方法如下所示:
get(boost::weak_ptr<TMyType> pMyType)
{
boost::shared_ptr<TMyType> pGOOD = pMyType.lock();
if (pGOOD != NULL)
{
// Do something with pGOOD
}
}
3. 在普通原始指针上测试 null 吗?这可能吗?
get(TMyType * pMyType)
{
if(pMyType != NULL){ //do something }
}
I have a vector of pointers to objects created with new. Multiple threads access this vector in a safe manner with various gets/sets. However, a thread may delete one of the objects, in which case another thread's pointer to the object is no longer valid. How can a method know if the pointer is valid? Options 1 and 2 actually seem to work well. I don't know how they will scale. What is the best approach? Is there a portable version 3?
Testing for pointer validity examples that work:
1. Use integers instead of pointers. A hash (std::map) checks to see if the pointer is still valid. Public methods look like:
get(size_t iKey)
{
if((it = mMap.find(iKey)) != mMap.end())
{
TMyType * pMyType = it->second;
// do something with pMyType
}
}
2. Have a vector of shared_ptr. Each thread tries to call lock() on its weak_ptr. If the returned shared_ptr is null we know someone deleted it while we were waiting. Public methods looks like:
get(boost::weak_ptr<TMyType> pMyType)
{
boost::shared_ptr<TMyType> pGOOD = pMyType.lock();
if (pGOOD != NULL)
{
// Do something with pGOOD
}
}
3. Test for null on plain raw pointers? Is this possible?
get(TMyType * pMyType)
{
if(pMyType != NULL){ //do something }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
#3 不起作用。删除指针并将其设置为 NULL 不会影响指向同一对象的其他指针。您无法使用原始指针来检测对象是否被删除。
#1 实际上是一个指向指针的指针。如果您始终通过该指针访问它并且能够锁定它。如果没有的话,如果成功获取后在另一个线程中删除了会怎样?
#2 是这种想法的标准实现,并且该模式在许多库中使用。锁定手柄,获取指针。如果你得到它,就使用它。如果没有,它就消失了。
#3 will not work. Deleting a pointer and setting it to NULL doesn't affect other pointers that are pointing to the same object. There is nothing you can do with raw pointers to detect if the object is deleted.
#1 is effectively a pointer to a pointer. If you always access it through that pointer and are able to lock it. If not, what happens if it's deleted in another thread after you successfully get it?
#2 is the standard implementation of this kind of idea, and the pattern is used in many libraries. Lock a handle, getting a pointer. If you get it, use it. If not, it's gone.