Linux实验全纪录之 多线程实现单词统计工具

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

pthread_mutex_t counter_clock=PTHREAD_MUTEX_INITIALIZER;


int main(int ac,char *av[])
{
  void *count_words(void *);
  if(ac!=3)
  {
    printf("Usage:%s file1 file2\n",av[0]);
    exit(1);
  }
 

  pthread_t tidp1,tidp2;
  int error1,error2;
  error1=pthread_create(&tidp1,NULL,count_words,av[1]);
  error2=pthread_create(&tidp2,NULL,count_words,av[2]);
  pthread_join(tidp1,NULL);
  pthread_join(tidp2,NULL);
  return 0;
}

void *count_words(void *f)
{
  char *filename=(char *)f;
  FILE *fp;
  int c,prevc='\0';
  int total_words=0;

  if((fp=fopen(filename,"r"))!=NULL){
    while((c=getc(fp))!=EOF)
    {
      if(!isalnum(c) && isalnum(prevc)){
         pthread_mutex_lock(&counter_clock);
         total_words++;
         pthread_mutex_unlock(&counter_clock);
       } 
       prevc=c;
    }
    fclose(fp);
    printf("total_words=%d\n",total_words);
  }else{
        perror(filename);
  }
  return NULL;
}
int total_words=0;要放在计数的函数里面

isalnum判断是字母还是数字;

编译格式要写成 gcc ***.c -o 可执行文件名 -lpthread


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值