Archived:Memory allocation in multithreaded Symbian C++ applications
Article Metadata
Compatibility
S60 2nd Edition, FP1, FP2, FP2
S60 3rd Edition
S60 3rd Edition FP1
Article
Overview
Calls like User::Alloc() and User::Available() are not thread safe if used in multiple threads with a shared heap.
Description
User::Alloc() and User::Available() calls are not thread safe by themselves. In a multithreaded application it is possible for the parent thread to specify the heap used by a child thread. There are two options: dedicated heap and shared heap. If two or more threads operate on a shared heap, then synchronization (e.g. with mutexes) is required.
Solution
1) Shared heap:
IMPORT_C TInt Create( const TDesC &aName,
TThreadFunction aFunction,
TInt aStackSize,
RAllocator *aHeap,
TAny *aPtr,
TOwnerType aType = EOwnerProcess );
If the aHeap parameter is set as NULL in the above call, then the thread will be sharing a heap memory with the parent thread.
In this case, memory allocation should be synchronized in their respective threads:
RMutex sharedMutex;
...
sharedMutex.Wait();
array[i] = User::Alloc( bytesToAlloc );
sharedMutex.Signal();
sharedMutex.Wait();
TInt heapSize = User::Available( largestBlock );
sharedMutex.Signal();
2) Dedicated heap:
When the following overloaded version of RThread::Create() is used, the new thread will use its own independent heap.
IMPORT_C TInt Create( const TDesC &aName,
TThreadFunction aFunction,
TInt aStackSize,
TInt aHeapMinSize,
TInt aHeapMaxSize,
TAny *aPtr,
TOwnerType aType = EOwnerProcess );
With separate heaps, the memory allocation calls do not have to be synchronized.


(no comments yet)