1

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 ?

enter image description here

proton
  • 658
  • 1
  • 7
  • 26

2 Answers2

3

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.

Minthos
  • 900
  • 4
  • 13
  • Actually private heaps aren't a bad idea. The consequent implication is that you can't share memory between threads. You would then have to share data via explicit IPC (pipes, etc). This is then becoming more like CSP, which is a good way of avoiding deadlock, livelock, etc. So not such a bad idea... – bazza Jun 24 '13 at 18:52
  • Yes, that's true. Threads in the traditional sense have access to each others' data, but if you remove that requirement you can make things much cleaner. – Minthos Jun 24 '13 at 19:59
  • @Minthos: Generic solution for a generic problem. – proton Jun 25 '13 at 11:11
1

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).

Suvarna Pattayil
  • 5,136
  • 5
  • 32
  • 59