zoukankan      html  css  js  c++  java
  • Linux_C pthread 关于多线程一个简单的程序

     1 /*******************************************************************************
     2  * twordcount.c threaded word counter for two files
     3  */
     4 #include <stdio.h>
     5 #include <pthread.h>
     6 #include <ctype.h>
     7 
     8 int total_words;
     9 pthread_mutex_t counter_lock=PTHREAD_MUTEX_INITIALIZER;//互斥锁
    10 
    11 int main(int argc, char* argv[]) {
    12   pthread_t t1, t2;
    13   void * count_words(void*);
    14   pthread_create(&t1, NULL, count_words, (void*)argv[1]);
    15   pthread_create(&t2, NULL, count_words, (void*)argv[2]);
    16   pthread_join(t1, NULL);
    17   pthread_join(t2, NULL);
    18   printf("%5d: total words 
    ", total_words);
    19 }
    20 
    21 void* count_words(void* file) {
    22   char* filename=(char* ) file;
    23   FILE* fp;
    24   int c, prevc='';
    25   if((fp=fopen(filename, "r"))!=NULL) {
    26     while((c=fgetc(fp))!=EOF) {
    27       if(!isalnum(c) && isalnum(prevc)) {
    28     pthread_mutex_lock(&counter_lock);
    29     total_words++;
    30     pthread_mutex_unlock(&counter_lock);
    31       }
    32       prevc=c;
    33     }
    34     fclose(fp);
    35   }else{
    36     perror("fopen");
    37   }
    38   return NULL;
    39 } 

    gcc twordcount.c -o twordcount -lpthread

    ./twordcount file1 file2

  • 相关阅读:
    易语言常用源码
    ci的数据库地址
    格式化输出php数组
    mysql插入表情问题
    线程、进程与协程2
    线程、进程与协程
    if __name=='__main__"的作用
    动态导入模块
    面向对象补充之方法
    getpass模块
  • 原文地址:https://www.cnblogs.com/wizzhangquan/p/4116604.html
Copyright © 2011-2022 走看看