Ubuntu——多线程实现单词统计工具

解决方案

区分单词原则:凡是一个非字母或数字的字符跟在字母或数字的后面。那么这个字母或数字就是单词的结尾。
允许线程使用互斥锁来修改临界资源,确保线程间的同步或协作。如果两个线程需要安全地共享一个公共计数器,需要把公共计数器加锁线程需要访问称为互斥锁的变量,它可以使线程间更好的工作,避免对于资源的访问冲突。

具体实现

#include 
#include 
#include 
#include 
//互斥信号量
pthread_mutexattr_t counter_clock;
//公共计数器
int total_word = 0;
int main(int argc,char*argv[])
{
    void *count_words(void*);
//    调试格式
    if(argc!=3){
        printf("Usage:%s file1 file2\n",argv[0]);
        exit(1);
    }
//    线程t1,t2
    pthread_t t1,t2;
    int res;
//    初始化临界区
    res = pthread_mutex_init(&counter_clock,NULL);
    if(res!=0){
        perror("Mutex initialization failed\n");
        exit(EXIT_FAILURE);
    }
//    创建线程1
    res = pthread_create(&t1,NULL,count_words,argv[1]);
    printf(" Thread 01 creating...\n");
    if(res!=0){
        perror("Thread create failly\n");
        exit(EXIT_FAILURE);
    }else{
        printf(" Thread 01 create successfully!\n");
    }
//    创建线程2
    res = pthread_create(&t2,NULL,count_words,argv[2]);
    printf(" Thread 02 creating...\n");
    if(res!=0){
        perror("Thread create failly\n");
        exit(EXIT_FAILURE);
    }else{
        printf(" Thread 02 create successfully!\n");
    }
//    让线程1进入等待态
    res = pthread_join(t1,NULL);
    printf(" Thread 01 joinning...\n");
    if(res!=0){
        perror("Thread join failly\n");
        exit(EXIT_FAILURE);
    }else{
        printf(" Thread 01 joined successfully!\n");
    }
//    让线程2进入等待态
    res = pthread_join(t2,NULL);
    printf(" Thread 02 joinning...\n");
    if(res!=0){
        perror("Thread join failly\n");
        exit(EXIT_FAILURE);
    }else{
        printf(" Thread 02 joined successfully!\n");
    }
//    输出统计出来的单词总数
    printf("There are %d words in two files\n",total_word);
    pthread_mutex_destroy(&counter_clock);
    return 0;
}
//  线程函数,即统计一个文件的单词个数函数
void *count_words(void *f){
    char *filename = (char *)f;
    FILE *fp;
    int c;
    int prevc = '\0';
    if((fp=fopen(filename,"r"))!=NULL){
        while((c=getc(fp))!=EOF){
            if(!isalnum(c)&&isalnum(prevc)){
                pthread_mutex_lock(&counter_clock);//   线程加锁
                total_word++;
                pthread_mutex_unlock(&counter_clock);//线程解锁
            }
            prevc = c;
        }
        fclose(fp);
    }else{
        perror(filename);
    }
    return NULL;

}

调试

1.Linux进入root

sudo su

2.打开源文件所在路径

cd path(path根据具体情况而定)

3.创建测试文档file1.txt和file2.txt

vim file1.txt
vim file2.txt

vim基础教程
4.编译(gcc编译)

gcc sourcefilename.c -lpthread

5.调试

./a.out file1.txt file2.txt

你可能感兴趣的:(Ubuntu——多线程实现单词统计工具)