Maximum number of threads that can be created within a process in C

In this article, we will explore how to determine the maximum number of threads that can be created within a process in C. Understanding thread limits is crucial for developing efficient multi-threaded applications.

A thread is a lightweight process that can be independently managed by the scheduler. Multiple threads can be associated with a single process, and they require less time for context switching compared to processes. Threads share memory with their peer threads and require fewer resources for creation and termination.

Syntax

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine)(void*), void *arg);

Approach

The program uses the following approach −

  • Create a simple thread function that performs minimal work
  • Use a loop to continuously create threads until pthread_create() fails
  • Count the number of successful thread creations
  • Display the maximum count when thread creation fails

Note: To compile this program, you need to link the pthread library using -lpthread flag:
gcc program.c -lpthread -o program

Example

Here's a complete program to find the maximum number of threads −

#include <pthread.h>
#include <stdio.h>

/* Simple thread function that does minimal work */
void *create(void *arg) {
    return NULL;
}

int main() {
    int max = 0, ret = 0;
    pthread_t th;
    
    /* Create threads until pthread_create fails */
    while (ret == 0) {
        ret = pthread_create(&th, NULL, create, NULL);
        max++;
    }
    
    /* Subtract 1 because last iteration failed */
    max--;
    
    printf("Maximum threads that can be created: %d<br>", max);
    return 0;
}
Maximum threads that can be created: 5741

Key Points

  • The output varies each time the program runs due to system resource availability
  • Thread limits depend on available memory, system configuration, and ulimit settings
  • Each thread consumes stack space (typically 8MB on Linux systems)
  • The program decrements the counter because the last pthread_create() call fails

Conclusion

The maximum number of threads depends on system resources and configuration. This method provides a practical way to determine thread limits at runtime, which is essential for resource planning in multi-threaded applications.

Updated on: 2026-03-15T12:55:08+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements