线程有另外一个名字叫Light Weight Process,
但是到底有多Light,我是一直没有太多直观感觉的。
根据书上所说,线程和进程的主要区别有二:
1. 创建开销
2. IPC代价
首先,创建线程的开销比进程低得多,
“线程的创建可能比进程的创建快10~100倍”(UNP),
这篇日志就是我对Linux下进程与线程创建速度测试的一个记录。
环境:
2.6.27-14-generic #1 SMP i686 GNU/Linux
进程用fork创建,而线程使用pthread库。
fork.c
#include <unistd.h> #include <stdlib.h> #include <stdio.h> int Fork(int i) { if( fork() == 0 ) { printf("%d\n", i); exit(0); } } int main(int c, char **v) { if(c != 2) { fprintf(stderr, "Usage: %s count\n",v[0]); return 0; } int iCount = atoi(v[1]); int i = 0; while( i < iCount ) { Fork(i); i++; } return 0; }
pthread.c
#include <pthread.h> #include <stdio.h> void thread(void *p) { printf("%d\n", *(int *)p); } int main(int c, char **v) { if(c != 2) { fprintf(stderr, "Usage: %s count\n",v[0]); return 0; } int iCount = atoi(v[1]); int i = 0; while( i < iCount ) { pthread_t pid; pthread_create(&pid, NULL, thread, (void *)&i); i++; } }
下面是测试结果:
fork pthread
1 0.003 0.011
10 0.007 0.004
100 0.123 0.013
1000 0.277 0.152
10000 1.423 0.467
的确快很多,但也没达到100倍。
下次再比较一下调度的性能。
近期评论