c++ - Thread safety for overloaded operator new -
though standard doesn't guarantee thread-safety new
, of multi-threading operating systems support thread-safe operator new
.
i implementing own memory management dynamic allocation of class
(say myclass
) in code. thread safety of myclass
, may have use pthread
or boost::
library.
i thought if new
already thread safe can overload myclass
, leverage safety without worrying using libraries.
class myclass { // data public: void* operator new (size_t); void operator delete (void*); };
is fair assumption c++03 systems/compilers?
edit: since question not followed few users. detailing part:
if have 2 threads new int()
, new int()
, 2 unique memory addresses returned. now, in overloaded myclass::new
not using global ::new()
or threading library; own memory manager (which doesn't know threads). pseudo code:
char pool[big_size]; void* myclass::operator new (size_t size) { // memory 'pool' without using thread library return p; }
my assumption is, since global ::new
thread safe, overloaded operator new
should thread-safe. in other words, compiler should emitting thread-safety related code wherever encounters new
keyword. correct assumption ?
it is.
however note in c++11 new thread safe.
of course, when you add thread unsafe code, makes operator new
thread unsafe.
following edit (which changed whole question):
the assumption compiler adds thread safety code around new call pretty wrong. sane implementations add thread safety within inner implementation of operator new (already because of efficiency considerations per-thread memory pools).
that is, when write thread unsafe allocation function, naming operator new
not magically make thread safe, other function, special way invoked.
Comments
Post a Comment