????????????????????????
??????????????????50000??
???????????????
// fork.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#define NFORKS 50000
void do_nothing()
{
int i;
i= 0;
}
int main(int argc?? char *argv[])
{
int pid?? i?? status;
for (i=0; i<NFORKS; i++) {
/*** error handling ***/
if ((pid = fork()) < 0 ) {
printf ("fork failed with error code= %d "?? pid);
exit(0);
}
/*** this is the child of the fork ***/
else if (pid ==0) {
do_nothing();
exit(0);
}
/*** this is the parent of the fork ***/
else {
waitpid(pid?? &status?? 0);
}
}
exit(0);
}
??????????????
?????????????????50000??
// pthread_create.c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NTHREADS 50000
void *do_nothing(void *null)
{
int i;
i=0;
pthread_exit(NULL);
}
int main(int argc?? char *argv[])
{
int rc?? i;
pthread_t tid;
for (i=0; i<NTHREADS; i++) {
rc = pthread_create(&tid?? NULL?? do_nothing?? NULL);
if (rc) {
printf("ERROR; return code from pthread_create() is %d "?? rc);
exit(-1);
}
/* Wait for the thread */
rc = pthread_join(tid?? NULL);
if (rc) {
printf("ERROR; return code from pthread_join() is %d "?? rc);
exit(-1);
}
}
pthread_exit(NULL);
}
????????
????gcc fork.c -o fork -Wall
????gcc pthread_create.c -o pthread_create -Wall
???????
??????????????
????$ cat /proc/cpuinfo | grep name | uniq
????model name: AMD Athlon(tm) 64 X2 Dual Core Processor 5200+
????$ uname -a
????Linux Mint 3.16.0-36-generic #48~14.04.1-Ubuntu SMP Wed Apr 15 13:11:28 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
?????????????????????????
????$ time ./fork
????real0m12.539s
????user0m0.124s
????sys0m13.070s
?????????????????????????
????$ time ./pthread_create
????real0m1.995s
????user0m0.503s
????sys0m1.821s