Re: Idea for custom thread-safe STL allocator?

From: Brian Genisio (BrianGenisio_at_yahoo.com)
Date: 01/12/04


Date: Mon, 12 Jan 2004 13:41:45 -0500
To: tom_usenet <tom_usenet@hotmail.com>

tom_usenet wrote:

> On Mon, 12 Jan 2004 12:25:22 -0500, Brian Genisio
> <BrianGenisio@yahoo.com> wrote:
>
>
>>Hi all,
>>
>>I am developing some software, that creates a tree of information. For
>>each node, currently I am overriding the new operator, because it is a
>>requirement that after initialization, no new memory may be allocated.
>>
>>It also needs to be thread safe, and each thread has a context, so any
>>allocation of nodes currently looks like this:
>>
>>new (context) Node(...);
>>
>>My allocator uses the context to keep memory from different threads safe.
>>
>>I want to use STL, and write a custom allocator template for passing to
>>the STL containers (map and vector specifically).
>>
>>The only problem, is that I need to figure out a way to have the STL use
>>the context as well, when it calls the allocator. I cant figure out a
>>way to tell the custom STL allocator to have a custom parameter stored
>>in the class before container initialization.
>>
>>Any ideas?
>
>
> template <class T>
> class myallocator
> {
> Context m_context;
> public:
> //allocator typedefs
>
> template <class U>
> struct rebind
> {
> typedef myallocator<U> other;
> };
>
> myallocator(Context const& context)
> :m_context(context)
> {
> }
>
> template <class U>
> myallocator(myallocator<U> const& other)
> :m_context(other.m_context)
> {
> }
>
> template <class U>
> myallocator& operator=(myallocator<U> const& other)
> {
> m_context = other.m_context;
> return *this;
> }
>
> T* allocate(size_type n, void* hint = 0)
> {
> return ::operator new(n * sizeof(T), m_context);
> }
>
> //etc.
> };
>
> Tom
>
> C++ FAQ: http://www.parashift.com/c++-faq-lite/
> C FAQ: http://www.eskimo.com/~scs/C-faq/top.html

Thanks for the info... I is very useful. The only question I have: How
does m_context ever get set?

Lets say I use a list of ints:

std::list<int, myallocator<int>> myList;

How do I get the context information in to the container's copy of the
allocator?

Thanks a lot,
Brian