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 \n", total_words);
19 }
20 
21 void* count_words(void* file) {
22   char* filename=(char* ) file;
23   FILE* fp;
24   int c, prevc='\0';
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

posted on 2014-11-23 15:31  Zachary_wiz  阅读(187)  评论(0编辑  收藏  举报

导航