How the heap is managed in the multi-threaded environment ?
- Is it shared among the threads or each thread has its independent heap ?
- If both are possible then which is the recommended approach ?
How the heap is managed in the multi-threaded environment ?
The heap can be shared and protected by a mutex. This is the simplest solution and works well in most cases.
You can have a heap for each thread, but then you have to decide whether you want to allow a deallocation to happen from any thread or only from the thread that made the allocation. Either way it can get pretty hairy. This can a more scalable solution if you have lots of threads and lots of allocations.
Talking about pthreads
,
From the man page,
A single process can contain multiple threads, all of which are executing the same program. These threads share the same global memory (data and heap segments), but each thread has its own stack (automatic variables).
The heap is the same for all threads but the access would depend on the scope of variable used to access the allocated memory.
void* thFn(void*)
{
char* c = new char[5];
//etc
delete[] c;
}
In this case, memory will be allocated on the heap. But c
is local to each pthread. Other pthreads
can possibly read from that location (retrieving correct values, until memory is released by the thread that allocated it ) if they are allowed to (If they obtain the address somehow).