Re: new and delete from different threads
Dilip wrote:
I am aware that the C++ standard in its present form does not say
anything about threads, however I do have a relevant question.
You could frame it in terms of Boost.Threads, since something along
those lines will likely be included in C++09. Then it would be on
topic. :-)
I am working on Windows XP/VC++ 8.0.
Is there a problem new'ing a bunch of objects from one thread and
deleting them in another? I do something like:
struct GenericPointerDeleter
{
template<typename T>
void operator()(T* p)
{
if (ptr != 0)
{
delete ptr;
ptr = 0;
}
}
};
First, there's no need to check for null before deleting. Second,
zeroing the pointer is generally unnecessary, though it might be useful
if you reuse the pointer (doesn't look like you do below) but such
reuse is often considered bad practice. Lastly, you're duplicating
existing functionality. You could use std::tr1::shared_ptr (aka
boost::shared_ptr) for a smart pointer that works with standard
containers.
typedef vector<classofpointers*> vecptrs;
If you do this...
typedef vector< shared_ptr<classofpointers> > vecptrs;
int main()
{
vecptrs myptrs;
CreateThread(...... (LPVOID)&myptrs........);
// use some platform specific API to wait until
threadcallbackroutine terminates
pseudo_wait_for_terminate(threadcallbackroutine);
for_each(myptrs.begin(), myptrs.end(), GenericPointerDeleter());
....then this is completely unnecessary. It is done automagically by the
destructors.
}
DWORD WINAPI threadcallbackroutine(LPVOID param)
{
vecptrs* my_ptrs = static_cast<vecptrs*>(param);
my_ptrs->push_back(new classofpointers());
return 0;
}
I have vastly simplified what is essentially happening in my
application...
Should I be careful about new'ing and deleting from the same thread?
That could be platform specific. <OT>But in your case it probably
doesn't matter.</OT>
Cheers! --M