OpenMP

OpenMP中一个变量可以有三种类型,即shared、private和reduction,默认为shared,除非如下三种特别情况:

一、在并行for循环中紧临parallel for 语句的循环变量是私有的;

二、并行区域代码块里的声明的变量是私有的;

三、所有通过private,firstprivate,lastprivate和reduction子句声明的变量为私有变量。

#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main(int argc, char *argv[])
{
  ifstream ifs(argv[1]);
  string name;
  map<string, int> brands;
  while (!ifs.eof()) {
    getline(ifs, name);
    map<string, int>::const_iterator it = brands.find(name);
    if (it == brands.end()) {
      brands[name] = 1;
    } else {
      brands[name] = it->second + 1;
    }
  }

  vector<string> names;
  map<string, int>::const_iterator it;
  for (it = brands.begin(); it != brands.end(); ++it) {
    names.push_back(it->first);
  }
  vector<int> counts(names.size());

#pragma omp parallel
{
  int i;
  #pragma omp for
  for (i = 0; i < names.size(); ++i) {
    int count = 0;
    map<string, int>::const_iterator it2;
    for (it2 = brands.begin(); it2 != brands.end(); ++it2) {
      string name = it2->first;
      if (name.find(names[i]) != string::npos) {
        count += it2->second;
      }
    }

    counts[i] = count;
  }
}

  for (int i = 0; i < names.size(); ++i) {
    cout << names[i] << "	" << counts[i] << endl;
  }
  
  return 0;
}
原文地址:https://www.cnblogs.com/agnostic/p/3795107.html