How to share heaps

Heaps may be shared between threads within a process.

When a new thread is created:

  • it can use the same heap as the thread which is doing the creating.

  • it can use the heap which has been explicitly created for it by the thread which is doing the creating.

  • it can use the heap automatically created for it by the operating system.

Only in the first two cases is the heap being shared.

Both are achieved by using the version of RThread::Create() prototyped as:

TInt Create(const TDesC& aName,
            TThreadFunction aFunction,
            TInt aStackSize,
            RHeap* aHeap,
            TAny* aPtr,
            TOwnerType aType=EOwnerProcess);

If aHeap is NULL, the new thread uses the same heap as the parent thread. For example:

RThread t;
_LIT(KTxtShared1,"Shared1");
...             ...
TInt r=t.Create(KTxtShared1,
                threadEntryPoint,
                KDefaultStackSize,
                NULL,
                NULL);

The calling thread can create a new heap using User::ChunkHeap() or UserHeap::ChunkHeap() (this is the same function; the User class is derived from UserHeap) and pass this heap to the RThread::Create() function. For example:

_LIT(KTxtShare,"Share");
_LIT(KTxtShared1,"Shared1");
...
RHeap* pH=User::ChunkHeap(KTxtShare,0x1000,0x100000);
RThread t;
TInt r=t.Create(KTxtShared1,
                threadEntryPoint,
                KDefaultStackSize,
                pH,NULL);

The new heap is contained within its own chunk.

If the creating thread no longer has any interest in this explicitly created heap, it can close it by calling Close(). Note that the corresponding call to Open() was done automatically by User::ChunkHeap(). The function Open() should be used to re-open the heap for sharing; this increases the access count.

Note that Open() can only be called on a heap created using User::ChunkHeap().

The heaps which are created automatically for a thread should not be closed with a call to Close() since the chunk in which the heap is created contains the thread's stack as well as the heap. In this case, if Close() is called the thread is panicked.