序言
linux环境中,线程是由系统调用clone()实现的.
clone()的复制程度高就相当于fork(),clone()的复制程度低就相当于pthread_create().
fork()创建子进程时复制了父进程的内存空间,所以父子进程资源访问较远.
线程与线程组首线程共享同一内存空间,所以线程组首线程和线程组弟线程资源访问近.
那么按理说线程的创建效率应该比进程的创建效率高,来实验下.
创建2000个进程
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
unsigned int process_num_created = 0;
unsigned int process_num_need = 2000;
pid_t pid = -1;
time_t time_start = 0;
time_t time_end = 0;
time_start = time(NULL);
for (;;)
{
if (process_num_need < 1)
{
break;
}
pid = fork();
// 父进程产生子进程失败
if (pid == -1)
{
fprintf(stderr,"fork() error\n");
break;
}
// 子进程
else if (pid == 0)
{
exit(0);
}
// 父进程
else
{
process_num_need--;
process_num_created++;
continue;
}
}
time_end = time(NULL);
fprintf(stdout,"process_num_created:%d,time_deta:%ld\n",process_num_created,(time_end - time_start));
exit(0);
}
创建2000个线程
#include <time.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *fun(void *argv)
{
return(NULL);
}
int main(int argc,char **argv)
{
unsigned int pthread_num_created = 0;
unsigned int pthread_num_need = 2000;
pthread_t tid;
int ret = -1;
time_t time_start = 0;
time_t time_end = 0;
time_start = time(NULL);
for (;;)
{
if (pthread_num_need < 1)
{
break;
}
ret = pthread_create(&tid,NULL,fun,NULL);
if (ret != 0)
{
fprintf(stderr,"pthread_create error\n");
break;
}
else
{
pthread_num_need--;
pthread_num_created++;
continue;
}
}
time_end = time(NULL);
fprintf(stdout,"pthread_num_created:%d,time_deta:%ld\n",pthread_num_created,(time_end - time_start));
exit(0);
}
现象
环境是wsl,果然如此.