什么时候使用多线程

使用多线程为什么可以提高效率呢?

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);
}


main2.c

#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比较多的时候,可以使用多线程提高效率。此时线程和线程是可以天然的异步工作。









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值