Get the no. of threads spawned in a C program

Hello
Is there a way to get the no. of threads spawned by a program in C?
There is no function in pthread.h that does this. :frowning:

Hi,
This is totally OS dependent. In think WIndows allow 1024 threads.

Do you want to know how many threads a process is allowed to create?
If that's the case then on AIX sysconf(_SC_THREAD_THREADS_MAX) will tell you the max number of threads allowed within a process.

I think the OP wants to now how many threads an application has created, not the maximiun possible.

It is generally possible to determine the number of threads from within a C program. However, how it is done is very OS-specific. If you tell us your platform and OS version, somebody here on this forum should be able to help you.

Thats not what I am looking for. I have written a C program that spawns posix threads using pthread_create. I want to programmatically get the no. of threads spawned by the program at some instance of time in the program. There is no function in pthread.h that does this. So I was wondering if there is a way to do it.

I am running my program on a Linux box that runs OpenSUSE 11.

In that case it only depends on how you go about creating threads within your C program especially if threads create other threads using nested function calls.

If you call pthread_create in a master thread or main program it is easy. This sit eh total numbers of threads created, not currently active threads

int thread_count=0;
...................
if(pthread_create(.....) == 0) thread_count++;

If "everybody" creates a thread, then you need to create a static mutex then a static integer variable in shared memory, initialize it to zero. Everybody calling pthread_create does this:

wait on mutex
get mutex & add one to the global counter;
release the mutex

pthreads have these basic calls (plus a lot of others)

create & destroy a mutex
      pthread_mutex_init(),
      pthread_mutex_destroy()
      PTHREAD_MUTEX_INITIALIZER is a macro to create a static mutex - probably what you want.

Lock/unlock a mutex.      

      pthread_mutex_lock(),
      pthread_mutex_trylock(),
      pthread_mutex_unlock()

that lets you play with mutexes. You will have to pass the mutex address to all of your threads or they cannot use it.

Got it. Thank you.