多线程统计多个文件的单词数目

由标题我们就可以知道意思了,这里我只是将最后自己优化后的代码贴出来,其他版本以及请从我的资源中下载:http://download.csdn.net/detail/chenqiai0/5233058


#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<stdbool.h>

#define filenumbers 3//表示文件个数
#define filenamenum 256//表示文件名最长为256
int cal(char filename[256]);
void *thread_function(void *arg);

int wordcount=0;//三个文件总的单词数
int count[3]={0,0,0};//三个文件单词数初始值都是0
char filenames[filenumbers][filenamenum]={"file1","file2","file3"};

pthread_mutex_t  fileMutex;//定义一个互斥变量
int main()
{	int i=0;
	int flag;//用于判断操作是不是正确
	pthread_t thread[3];
//	int count1=0,count2=0,count3=0;

	/*互斥锁初始化*/
	flag=pthread_mutex_init(&fileMutex,NULL);
	if(flag!=0)
	{
		perror("Mutex initalization failed!\n");
		return 1;
	}

	/*create pthread*/
	for(i=0;i<3;i++)
	{
		flag=pthread_create(&thread[i],NULL,thread_function,(void*)&filenames[i]);
		if(flag!=0)
		{
			perror("Thread creation failed!\n");
			return 1;
		}
	}


	//pthread_join(thread[0],(void**)&count1);
	//pthread_join(thread[1],(void**)&count2);
	//pthread_join(thread[2],(void**)&count3);
	for(i=0;i<3;i++)
	{
		pthread_join(thread[i],(void**)&count[i]);
	}

	wordcount=count[0]+count[1]+count[2];
	printf("总的单词数:%d\n",wordcount);
	return 0;
}





int cal(char filename[256])
{
	bool start;
	int count=0;//用于记录单词数
	char c;
	long int offset;
	FILE *fp;
	fp=fopen(filename,"r");
	if(fp==NULL)
	{
		printf("open filed!\n");
		exit(EXIT_FAILURE);
	}

	fseek(fp,0,SEEK_SET);
	start=true;//start=0用于表示单词的开始,start=1表示没有
	while(feof(fp)==0)//feof(fp)==0 表示还没有到文件尾
	{
		fread(&c,1,1,fp);
		if(c==' '&&start==1)
		{
			start=1;
		}
		else if(c!=' '&&start==1)
		{
			start=0;
			count++;
		}
		else if(c==' '&&start==0)
		{
			start=1;
		}
	}
	printf("%s",filename);
	printf("word count:%d\n",count);
	return count;
}
void *thread_function(void *arg)
{
		return (void*)cal((char*)arg);
}
相信大家都更好的办法,请留言!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值