使用多线程为什么可以提高效率呢?
io是关键。很多的应用要使用io,但是cpu是很快的,io往往是很慢的。
看代码
main1.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
char *p;
void sys_error(int errnum)
{
perror(strerror(errnum));
exit(-1);
}
void *
func(void *arg)
{
int tmp = (int)arg;
printf("arg : %d\n", tmp);
char buf[1000] = {0};
int i = 0;
for (;i<10000000;++i) {
strcpy(buf, p);
strcpy(p, buf);
}
return NULL;
}
int
main(void)
{
p = (char *)malloc(1000);
strcpy(p,"11111111111111111111111111111111111111\
1111111111111111111111111111111111111111\
1111111111111111111111111111111111111111\
1111111111111111111111111111111111111111\
1111111111111111111111111111111111111111\
1111111111111111111111111111111111111111\
1111111111111111111111111111111111111111\
1111111111111111111111111111111111111111\
111111111111111111111111111111111111111\
1111111111111111111111111111111111111111");
pthread_t tid;
int res, i;
for (i = 0; i < 5; ++i) {
if ((res = pthread_create(&tid, NULL, func, (void *)i)) != 0)
sys_error(res);
}
pthread_exit(NULL);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
char *p;
void sys_error(int errnum)
{
perror(strerror(errnum));
exit(-1);
}
void *
func(void *arg)
{
int tmp = (int)arg;
printf("arg : %d\n", tmp);
char buf[1000] = {0};
int i = 0;
for (;i<10000000;++i) {
strcpy(buf, p);
strcpy(p, buf);
}
return NULL;
}
int
main(void)
{
p = (char *)malloc(1000);
strcpy(p,"11111111111111111111111111111111111111\
1111111111111111111111111111111111111111\
1111111111111111111111111111111111111111\
1111111111111111111111111111111111111111\
1111111111111111111111111111111111111111\
1111111111111111111111111111111111111111\
1111111111111111111111111111111111111111\
1111111111111111111111111111111111111111\
111111111111111111111111111111111111111\
1111111111111111111111111111111111111111");
pthread_t tid;
int res, i;
for (i = 0; i < 5; ++i)
func((void *)i);
}
main1.c 是5个多线程,每个线程运行一次func函数,func函数有大量的io操作。
main2.c是只有一个进程,调用了5次func函数,func函数有大量的io.
其中demo对应多线程的,a.out对应单进程的。
可以发现多线程的程序运行时间2.59 比2.74要少点,此时说明使用多线程的效果比单进程要好。因为多线程在一个线程Io的时候,cpu又去处理别的线程了,这样就提高了工作效率。而单进程即使cpu是空闲的,因为没有被的线程可以切换,只能在这里干等。而且在运行程序的时候可以发现,运行多线程的时候打印的数据是迅速的打印出来,然后处于等待状态。而单进程的打印时等一会打印一个,再等一会再打印一个。这也可以验证确实是这样的。
但是当io的工作量很小时,多线程没有提高效率,而且增加了线程切换的消耗,效率反而降低。
把上面的对应函数的大量的io去掉之后,总体的运行时间都减少了很多,而且多线程反而更慢。是0.04s,单进程是0.02s.
总结:当工作中io比较多的时候,可以使用多线程提高效率。此时线程和线程是可以天然的异步工作。