Am trying to parallelize the compression process using OpenMP. Currently trying to parallelize it while all threads uses the same dictionary. But error seems to occur when trying to add new contents to dictionary. Any suggestions on how to to parallelize it using openmp?
Exception thrown: read access violation. this was 0xFFFFFFFFFFFFFFDF. Errors occurs while executing the code below in openmp critical.
dict[next] = dict_size++;
current = string(1, c);
void lzw_parallel(const string& input, const string& output_file) {
// Initialize dictionary with single characters
unordered_map<string, int> dict;
for (int i = 0; i < 256; i++) {
dict[string(1, i)] = i;
}
vector<int> compressed;
int dict_size = 256;
string current;
double start_time = omp_get_wtime();
#pragma omp parallel for shared(dict, compressed, dict_size, current)
for (int i = 0; i < input.length(); i++) {
char c = input[i];
string next = current + c;
if (dict.find(next) != dict.end()) {
current = next;
}
else {
#pragma omp critical
{
compressed.push_back(dict[current]);
dict[next] = dict_size++;
current = string(1, c);
}
}
}
if (!current.empty()) {
#pragma omp critical
{
compressed.push_back(dict[current]);
}
}
// Write compressed data to file
ofstream outfile(output_file);
for (int i : compressed) {
outfile << i << " ";
}
// Print input and compressed lengths
cout << "Input length: " << input.length() << endl;
cout << "Compressed length: " << compressed.size() * 12 / 8 << endl;
// Print elapsed time
double end_time = omp_get_wtime();
printf("Work took %f seconds \n", end_time - start_time);
}