Поиск в текстовом файле всех слов, заданных в другом текстом файле.
Считается что первый файл — файл «словаря», в нем перечислены все слова, которые нужно найти, без повторений. Программа читает первый файл и создает массив из этих слов, а также по счетчику для каждого. Далее необходимое количество раз вызывается функция поиска.
Функция поиска открывает файл текста, читает его по слову и сравнивает прочитанное слово с нужным элементом массива. Если совпадают, то счетчик увеличивается.
В параллельном алгоритме потоки создаются для этой функции, мьютекс используется для разграничения доступа к счетчику.
1) Реализация последовательного алгоритма: posl_al2.c
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#define MAX 100
char str[MAX], dict[MAX][MAX], name[MAX];
int count[MAX];
void *search(void *);
int main (int argc, char** argv){
struct timeval ts; gettimeofday(&ts, NULL);
FILE *in;
in = fopen(argv[1], "r");
strcpy(name, argv[2]);
int i=0;
for (i=0; i<MAX; i++){dict[i][0]=0;}
if (!in) {
printf ("Can't open dict. file!\n");
return 1;
}
i=0;
while( feof(in)==0 ){
fscanf (in, "%s", dict[i]);
dict[i][strlen(dict[i])+1]=0;
i++;
}
int n = i;
int num;
for (num=0;num<n;num++){
search ( (void *)num);
}
for (i=0; i<MAX; i++){
if (strcmp(dict[i], "")!=0){
printf ("%s = %d\n", dict[i], count[i]);
}
}
fclose (in);
struct timeval te; gettimeofday(&te, NULL);
int time = (te.tv_sec - ts.tv_sec)*10^6 + (te.tv_usec - ts.tv_usec);
printf ("time: %d\n", time);
return 0;
}
void *search(void * attr){
FILE *text;
int cc = (int)attr;
text = fopen(name, "r");
if (!text) {
printf ("Can't open text file!\n");
}else{
char strlocal[MAX];
while (feof(text)==0){
fscanf(text, "%s", strlocal);
strlocal[strlen(strlocal) + 1] = 0;
if (strcmp(strlocal, "")!=0){
if (strcmp(strlocal, dict[cc])==0){
count[cc]++;
}
}
strlocal[0]=0;
}
fclose(text);
}
}
2) Реализация параллельного алгоритма: par_al.c
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <sys/time.h>
#define MAX 100
pthread_mutex_t mutex;
char str[MAX], dict[MAX][MAX], name[MAX];
int count[MAX];
void *search(void *);
int main (int argc, char** argv){
pthread_mutex_init (&mutex, NULL);
struct timeval ts; gettimeofday(&ts, NULL);
FILE *in;
in = fopen(argv[1], "r");
strcpy(name, argv[2]);
int i=0;
for (i=0; i<MAX; i++){dict[i][0]=0;}
if (!in) {
printf ("Can't open dict. file!\n");
return 1;
}
i=0;
while( feof(in)==0 ){
fscanf (in, "%s", dict[i]);
dict[i][strlen(dict[i])+1]=0;
i++;
}
int n = i;
pthread_t a[n];
int num;
for (num=0;num<n;num++){
pthread_create(&a[num], NULL, search, (void *)num);
}
for (num=0; num<n; num++){
pthread_join(a[num], NULL);
}
pthread_mutex_destroy (&mutex);
for (i=0; i<MAX; i++){
if (strcmp(dict[i], "")!=0){
printf ("%s = %d\n", dict[i], count[i]);
}
}
fclose (in);
struct timeval te; gettimeofday(&te, NULL);
int time = (te.tv_sec - ts.tv_sec)*10^6 + (te.tv_usec - ts.tv_usec);
printf ("time: %d\n", time);
return 0;
}
void *search(void * attr){
FILE *text;
int cc = (int)attr;
text = fopen(name, "r");
if (!text) {
printf ("Can't open text file!\n");
}else{
char strlocal[MAX];
while (feof(text)==0){
fscanf(text, "%s", strlocal);
strlocal[strlen(strlocal) + 1] = 0;
if (strcmp(strlocal, "")!=0){
if (strcmp(strlocal, dict[cc])==0){
pthread_mutex_lock(&mutex);
count[cc]++;
pthread_mutex_unlock(&mutex);
}
}
strlocal[0]=0;
}
fclose(text);
}
}
|