I'm fairly new to C, and this is my first time using pthread
. I am pretty sure I implemented it correctly, however I'd like to verify it is indeed executing the tasks parallel instead of sequentially. Here is my main.c
code:
main.c
#include "frequency.h"
/**
* The main function. Runs {@code getMedianWord()} in parallel threads for each file,
* then outputs the sorted elements in FileArray file_array.
*/
int main(int argc, char **argv) {
int actual_args = argc - 1;
pthread_t tid[argc];
for (int i = 0; i < actual_args; ++i)
pthread_create(&tid[i], NULL, getMedianWord, (void *) &argv[i + 1]);
for (int j = 0; j < actual_args; ++j)
pthread_join(tid[j], NULL);
qsort(file_array,
(size_t) actual_args,
sizeof(FileArray),
(int (*)(const void *, const void *)) file_cmp
);
for (int k = 0; k < actual_args; ++k)
printf("\n%s %d %s",
file_array[k].filename,
file_array[k].num,
file_array[k].median_word
);
pthread_exit(NULL);
}
frequency.c
...
void *getMedianWord(void *vargp) {
char *filename = *(char **) vargp;
WordArray word_array[MAX_WORDS];
FILE *fp = fopen(filename, "r");
char word[101];
int n = 0;
while (!feof(fp)) {
fscanf(fp, "%s", word);
insert_word(word_array, &n, word);
}
insert_arr(file_array, filename, n, word_array);
pthread_exit(NULL);
}
The intended code to be executed in parallel is the function getMedianWord
, which adds a result to a global array of structs (file_array
), and terminates via pthread_exit(NULL)
.
Please let me know if this is actually using threads properly, thanks!
PS. If you're interested in seeing the rest of my code, here it is.
getMedianWord
code directly. As posted, it is on the verge of being closed as hypothetical. \$\endgroup\$getMedianWord
, thanks!! \$\endgroup\$