#include #include #include #include /* max size of arrays */ #define STRING_SIZE 64 #define NUM_STRINGS 100000 /* the number of threads */ int num_threads; /* global variables, used to specify what to search for each thread */ char strings[NUM_STRINGS][STRING_SIZE]; int num_strings; char target[STRING_SIZE]; /* the function called for each thread */ void* search_thread(void* idp) { /* get our thread id */ int id = * (int*) idp; /* calculate the start and end points by evenly dividing the range */ int start = (num_strings / num_threads) * id; int end = start + (num_strings / num_threads) - 1; /* the last thread needs to do all remaining ones */ if (id == (num_threads - 1)) { end = num_strings; } /* search the array for the given string */ int i; for (i = start; i < end; i++) { if (strstr(strings[i], target)) { printf("%s", strings[i]); printf(" matches "); printf("%s", target); printf(" on line "); printf("%d", i); printf("\n"); } } return NULL; } /* the main thread loads up a file of strings and asks the user what to search for */ int main (int argc, char** argv) { /* get the number of threads */ if (argc < 2) { printf("Pass the number of threads to use!\n"); return 0; } else { num_threads = atoi(argv[1]); } /* read in the dictionary file! */ FILE* fp = fopen("words.txt", "r"); int i = 0; do { fscanf(fp, "%s", strings[i]); i++; } while (!feof(fp)); num_strings = i; /* ask the user what to search for */ printf("What text would you like to search for?\n"); scanf("%s", target); /* an array of threads */ pthread_t threads[num_threads]; int ids[num_threads]; /* spawn all threads */ for (i = 0; i < num_threads; i++) { ids[i] = i; pthread_create(&threads[i], NULL, search_thread, &ids[i]); } /* join all threads */ for (i = 0; i < num_threads; i++) { pthread_join(threads[i], NULL); } return 0; }