// mutual exclusive - > mutex (상호 배제)
// 크리티컬 섹션에 락을 걸어서 값을 변경할 때 접근하지 못하게함.
// 락걸린 동안 기다려야되니까 느려진다.
#include <stdio.h>
#include <pthread.h>
#include <ctype.h>
int total_word;
pthread_mutex_t counter_lock = PTHREAD_MUTEX_INITIALIZER; // mutex lock 변수 선언. 전역변수여야한다.
main(int ac, char* av[])
{
pthread_t t1,t2;
void *count_word(void*);
if(ac!=3)
{
printf("usage");
exit(1);
}
total_word = 0;
pthread_create(&t1,NULL,count_word,(void*)av[1]);
pthread_create(&t2,NULL,count_word,(void*)av[2]);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
printf("%5d: total word\n", total_word);
}
void *count_word(void* f)
{
char* filename = (char*) f;
FILE *fp;
int c, prevc = '\0';
if ((fp=fopen(filename, "r"))!= NULL)
{
while((c=getc(fp))!=EOF)
{
if(!isalnum(c)&&isalnum(prevc))
{
pthread_mutex_lock(&counter_lock); // 여기서 락걸고
total_word++;
pthread_mutex_unlock(&counter_lock); // 여기서 언락
}
prevc = c;
}
fclose(fp);
}
else
perror(filename);
return NULL;
}
'IT' 카테고리의 다른 글
(설계) Messenger with system call (0) | 2014.12.12 |
---|---|
two word count 4 (0) | 2014.12.09 |
two word count 1 .c (0) | 2014.12.09 |
print.c (0) | 2014.12.09 |
multi.c (0) | 2014.12.09 |