#include <stdio.h> #include <string.h> #include <pthread.h> pthread_mutex_t mtx; //переменная мьютекса typedef struct { char slovo[20]; char str[20]; int res; int col_words; } pthrData; void* process(void* thread_data) { pthrData* data = (pthrData*) thread_data; //создаем указатель на структуру pthread_mutex_lock(&mtx); printf("tread is work\n"); char* instr; double proc; data->col_words++; //количество слов instr = strstr(data->str, data->slovo); //ищем слово в строке if (instr != NULL) { data->res += strlen(data->slovo); //считаем символы } proc = (data->res + data->col_words - 1) * 100 / strlen( data->str); //вычисляем процент printf("%.2lf", proc); pthread_mutex_unlock(&mtx); usleep(50000); } void main(void) { pthread_mutex_init(&mtx, NULL); char S1[20], S2[20]; char sp[10] = " "; char* istr; int res = 0, col_w = 0, tmp, i = 0; double proc; printf("Enter S1, S2\n"); gets(S1); gets(S2); if (strlen(S1) <= strlen(S2)) { istr = strtok(S1, sp); while (istr != NULL) { col_w++; //считаем количество слов istr = strtok(NULL, sp); } printf("tre"); printf("%d", col_w); pthread_t* threads = (pthread_t*) malloc(col_w * sizeof( pthread_t)); //выделяем память под переменные потоков pthrData* threadData = (pthrData*) malloc(col_w * sizeof( pthrData)); //выделяем память под структуру, для отправки в функцию потока for (int i = 0; i < col_w; i++) { strncpy(threadData[i].slovo, istr, 20); strncpy(threadData[i].str, S2, 20); threadData[i].res = 0; threadData[i].col_words = 0; pthread_create(&(threads[i]), NULL, process, &threadData[i]); // создаем поток } for (int i = 0; i < col_w; i++) { pthread_join(threads[i], NULL); // блокируем потоки } free(threads); // чистим память free(threadData);// чистим память } return 0; } Comparison of strings of arbitrary content and output of percent similarity
Error - Segmentation fault. At the compilation stage it produces the following:
