added parallel code#10
Conversation
There was a problem hiding this comment.
Pull Request Overview
This PR introduces a parallel word counting implementation using OpenMP. The program reads a text file and counts words using multiple threads, then benchmarks the performance across multiple runs.
Key Changes
- Implements parallel word counting using OpenMP thread-based parallelization
- Adds command-line argument handling for file path and number of benchmark runs
- Includes timing statistics (min, max, avg) across multiple runs
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| double max = 0.0; | ||
| double sum = 0.0; | ||
| double avg = 0.0; | ||
| double *times = malloc(sizeof(double) * RUNS); |
There was a problem hiding this comment.
Missing null check after malloc. If memory allocation fails, the program will crash when accessing times[count] at line 126.
| double *times = malloc(sizeof(double) * RUNS); | |
| double *times = malloc(sizeof(double) * RUNS); | |
| if (!times) | |
| { | |
| perror("malloc"); | |
| return 1; | |
| } |
| if (i == 0) | ||
| { | ||
| local_count++; | ||
| } | ||
| else if (isspace((unsigned char)buf[i - 1])) | ||
| { | ||
| local_count++; | ||
| } |
There was a problem hiding this comment.
Word counting logic is incorrect for multi-threaded execution. Each thread checks if i == 0 to detect word start, but only thread 0 will have i == 0 as the actual start of the buffer. Other threads starting at start > 0 will incorrectly count a word at their chunk boundary if the character is non-space, even if it's in the middle of a word. This will lead to incorrect word counts.
There was a problem hiding this comment.
@copilot open a new pull request to apply changes based on this feedback
| { | ||
| local_count++; | ||
| } | ||
| else if (isspace((unsigned char)buf[i - 1])) |
There was a problem hiding this comment.
Out-of-bounds memory access when i == start and start > 0. Thread checks buf[i - 1] without verifying that i > start, which could access memory outside the thread's intended chunk range, potentially causing race conditions or incorrect results.
| else if (isspace((unsigned char)buf[i - 1])) | |
| else if (i > start && isspace((unsigned char)buf[i - 1])) |
| printf("avg time: %.6f seconds\n", avg); | ||
| printf("num of runs: %d\n", RUNS); | ||
| free(buf); | ||
| free(times); |
There was a problem hiding this comment.
Memory leak: times array is freed even when malloc at line 49 might have failed (no null check). Additionally, if malloc fails and returns NULL, calling free(NULL) is safe but the program should have exited earlier.
[WIP] Add fixes based on feedback for parallel code implementation
Closes #3
adds parallel code.
compile with: gcc -fopenmp parallel.c -O2 -o parallel
check: ./parallel -h for usage