I have a question about boost::shared_ptr<T>
.
There are lots of thread.
using namespace boost;
class CResource
{
// xxxxxx
}
class CResourceBase
{
public:
void SetResource(shared_ptr<CResource> res)
{
m_Res = res;
}
shared_ptr<CResource> GetResource()
{
return m_Res;
}
private:
shared_ptr<CResource> m_Res;
}
CResourceBase base;
//----------------------------------------------
// Thread_A:
while (true)
{
//...
shared_ptr<CResource> nowResource = base.GetResource();
nowResource.doSomeThing();
//...
}
// Thread_B:
shared_ptr<CResource> nowResource;
base.SetResource(nowResource);
//...
If Thread_A do not care the nowResource
is the newest, will this part of code have problem?
I mean when Thread_B do not SetResource()
completely, Thread_A get a wrong smart point by GetResource()
?
What does thread-safe mean?
If I do not care about whether the resource is newest, will the shared_ptr<CResource> nowResource
crash the program when the nowResource
is released or will the problem destroy the shared_ptr<CResource>
?
From the boost documentation:
shared_ptr
objects offer the same level of thread safety as built-in types. Ashared_ptr
instance can be "read" (accessed using only const operations) simultaneously by multiple threads. Differentshared_ptr
instances can be "written to" (accessed using mutable operations such asoperator=
or reset) simultaneously by multiple threads (even when these instances are copies, and share the same reference count underneath.)Any other simultaneous accesses result in undefined behavior.
So your usage is not safe, since it uses simultaneous read and write of m_res
. Example 3 in the boost documentation also illustrates this.
You should use a separate mutex that guards the access to m_res
in SetResource
/GetResource
.