threads and memory allocation

Hello!
First of all, forgive me for bad English.

When I starts new thread (pthread_create), system allocates some memory for it (for example, for thread's stack). I wonder when does it deallocate this memory? The problem is that I have a program which sometimes creates new threads and sometimes deletes it. And memory used by my program always increases and never decreases (I use top utility to watch for my program behaviour). And I wonder is it my bug or standard behaviour. It seems my program stops threads which are not needed anymore, but memory doesn't decrease and after some time pthread_create says that it can't create new thread.

I will really appreciate your help!

P.S. The system is Solaris 5.10, if it matters.

do you use pthread_exit to terminate your threads ?

Some memory mgt strategies keep all the memory that brk() gets for the process.

Are you calling pthread_cleanup_push() & pthread_cleanup_pop() ? Under some circumstances: if the (void *) arg == 0 nothing will happen. ie., you leave junk behind.

  1. Yes, I use cleanup_push and pop. Here is a part of my code:
void thread_cleanup(void* r) {
	ARunnable* runnable = static_cast<ARunnable*>(r);
	runnable->onClose();
	delete runnable;
}

void* thread_function(void* r) {
	CThread* th = static_cast<CThread*>(r);
	ARunnable* runnable = th->target();	
	pthread_cleanup_push(thread_cleanup, static_cast<void*>(runnable));
	try {
		runnable->run();
	}
	catch (...) {
		cerr << "error" << endl;
	}
	pthread_cleanup_pop(1);          // 0
	pthread_detach(th->thread());  // 1
	pthread_exit(NULL);                 // 2

	return NULL;
}

bool CThread::start() {
	int e = 0;
	
	if (0 != (e = pthread_create(&_thread, NULL, thread_function, static_cast<void*>(this)))) {
		return false;
	}

	return true;
}

As you see, I've tried to make a little wrapper for pthread_* routines. I've added lines labelled 1 and 2 because I thought it would make threads to deallocate memory. But it doesn't work.

Also I have some misunderstanding about pthread_cleanup_push and pop technics. Does the system return control to the thread_function after calling thread_cleanup, if thread_cleanup is called not from the line 0?