- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum number of threads that can be created within a process in C
Given the task is to find the maximum number of threads that can be created within a process in C.
A thread is lightweight process and can be independently managed by the scheduler. Because a thread is a component of a process, therefore multiple number of threads can be associated in a process and also it takes less time for context switching as it is lighter than the process.
Threads require less resources than the processes and they also share memory with its peer threads. All user level peer threads are treated as a single task by the operating system. Less time is required for their creation as well as termination.
The output will always be different every time the program is executed.
Approach used in the below program as follows
Create function void* create(void *) and leave it empty as it only demonstrates the work of the thread.
In main() function initialize two variables max = 0 and ret = 0 both of type int to store the maximum number of threads and the return value respectively.
Declare a variable “th” of type pthread_t.
Run a while loop with condition ret == 0 and put ret = pthread_create (&th, NULL, create, NULL);
Iterate max++ inside the loop.
Print max outside the loop.
Example
#include<pthread.h> #include<stdio.h> /*Leave the function empty as it only demonstrates work of thread*/ void *create ( void *){ } //main function int main(){ int max = 0, ret = 0; pthread_t th; //Iterate until 0 is returned while (ret == 0){ ret = pthread_create (&th, NULL, create, NULL); max++; } printf(" %d ", max); }
Output
5741