Re: thread-safe new and delete
Am 30.10.2010 18:46, schrieb Thomas Richter:
mpho schrieb:
How can I implement operators new and delete in a re-entrant and
thread-safe manner? OR are there libraries out there ready for
use?
The current ISO C++ standard has nothing to say about threads, so
there is nothing the standard can ensure. (This will change with
C++0x). However, threads are often supported as a compiler extension
by many C++ compilers. Then, however, I would expect from any
reasonable implementation that offers threads that it also offers
thread-safe operator new and operator delete implementations.
Actually, both C++ and VS are reasonable in this sense: Their
operator new/delete are thread-safe if thread support is turned on.
I don't think that this answers the OPs question. The question
was how *user code* could implement these operators re-entrant and thread-safe.
In fact, it will fortunately *not* be a matter of QoI, whether in C++0x
the library-provided news-handler is thread-safe or not - according to
18.6.1.4 [new.delete.dataraces] the following guarantees are provided:
"1 The library versions of operator new and operator delete, user
replacement versions of global operator new and operator delete, and
the C standard library functions calloc, malloc, realloc, and free shall
not introduce data races (1.10) as a result of concurrent calls from
different threads. Calls to these functions that allocate or deallocate
a particular unit of storage shall occur in a single total order, and
each such deallocation call shall happen before the next allocation (if
any) in this order."
There is indeed an inherent lack-of-safety problem if user
code would like to write his/her own new-handler which mimics
at least some parts of the implementation-provided version.
When trying to do that, you stumble across the problem, that
no non-modifying inspector for the current new-handler is
provided. You only have the modifying function:
new_handler set_new_handler(new_handler new_p) throw();
but the default behavior as described in [new.delete.single]/4
requires to inspect the new handler when the requested memory
cannot be provided, which is of-course a potential source of
a data race. This was also criticized in two national comments
against the FCD,
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3162.html#DE14
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3162.html#GB71
As a partial solution of this problem the following proposal
has been prepared:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3122.html
It is clear that this solution is not a perfect one, but at least
a minimum attempt of a fix of the current state.
HTH & Greetings from Bremen,
- Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]