码迷,mamicode.com
首页 > 编程语言 > 详细

Linux_C pthread 关于多线程一个简单的程序

时间:2014-11-23 15:51:45      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   div   

 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

Linux_C pthread 关于多线程一个简单的程序

标签:style   blog   io   ar   color   os   sp   for   div   

原文地址:http://www.cnblogs.com/wizzhangquan/p/4116604.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!