Skip to content

Commit 7f53ee7

Browse files
committed
Parallelize linear search in executeEngine-omp.c using two-phase approach with OpenMP (fixes #42)
1 parent 90a9a49 commit 7f53ee7

File tree

1 file changed

+39
-13
lines changed

1 file changed

+39
-13
lines changed

engine/omp/executeEngine-omp.c

Lines changed: 39 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -909,27 +909,53 @@ int isAttributeIndexed(struct engineS *engine, const char *attributeName) {
909909

910910
/* Performs a linear search through a given array of records based on the WHERE clause */
911911
record **linearSearchRecords(record **records, int num_records, struct whereClauseS *whereClause, int *matchingRecords) {
912-
// Allocate space for results array
913-
record **results = malloc(sizeof(record *));
914912
*matchingRecords = 0;
913+
914+
// Phase 1: Parallel identification of matching records using flags
915+
int *matchFlags = (int *)calloc(num_records, sizeof(int));
916+
if (!matchFlags) {
917+
return NULL; // Memory allocation failure
918+
}
915919

916-
// Iterate through all records and apply WHERE clause filtering
917-
for(int i = 0; i < num_records; i++) {
918-
record *currentRecord = records[i];
919-
bool matches = true;
920+
#pragma omp parallel
921+
{
922+
int localMatches = 0;
923+
924+
#pragma omp for nowait
925+
for(int i = 0; i < num_records; i++) {
926+
record *currentRecord = records[i];
927+
bool matches = true;
928+
929+
if (whereClause != NULL) {
930+
matches = evaluateWhereClause(currentRecord, whereClause);
931+
}
920932

921-
if (whereClause != NULL) {
922-
matches = evaluateWhereClause(currentRecord, whereClause);
933+
if (matches) {
934+
matchFlags[i] = 1;
935+
localMatches++;
936+
}
923937
}
924938

925-
// If record matches all conditions, add to results
926-
if (matches) {
927-
results = realloc(results, (*matchingRecords + 1) * sizeof(record *));
928-
results[*matchingRecords] = currentRecord;
929-
(*matchingRecords)++;
939+
#pragma omp atomic
940+
*matchingRecords += localMatches;
941+
}
942+
943+
// Phase 2: Serial collection of matching records into results array
944+
record **results = malloc((*matchingRecords) * sizeof(record *));
945+
if (!results) {
946+
free(matchFlags);
947+
return NULL; // Memory allocation failure
948+
}
949+
950+
int writeIndex = 0;
951+
for(int i = 0; i < num_records; i++) {
952+
if (matchFlags[i]) {
953+
results[writeIndex++] = records[i];
930954
}
931955
}
932956

957+
free(matchFlags);
958+
933959
// Return the array of matching records
934960
return results;
935961
}

0 commit comments

Comments
 (0)