C语言中进程内可创建的最大线程数
给定的任务是找到在 C 语言中进程内可以创建的最大线程数。
线程是轻量级进程,可以由调度程序独立管理。因为线程是进程的一部分,所以多个线程可以关联到一个进程中,并且由于它比进程更轻量级,因此上下文切换需要更少的时间。
线程需要的资源比进程少,并且它们还与同级线程共享内存。所有用户级同级线程都被操作系统视为单个任务。它们的创建和终止也需要更少的时间。
每次执行程序时,输出都会有所不同。
下面程序中使用的算法如下
创建函数 void* create(void *) 并将其留空,因为它只演示了线程的工作。
在 main() 函数中初始化两个变量 max = 0 和 ret = 0,它们都是 int 类型,分别用于存储最大线程数和返回值。
声明一个 pthread_t 类型的变量“th”。
运行一个 while 循环,条件为 ret == 0,并在其中放置 ret = pthread_create (&th, NULL, create, NULL);
在循环内迭代 max++。
在循环外打印 max。
示例
#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);
}输出
5741
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP