【发布时间】:2018-06-06 18:52:04
【问题描述】:
据我所知,以下玩具代码没有任何用处:
#include <iostream>
#include "omp.h"
using namespace std;
class OtherClass {
public:
OtherClass() {
cout << "hi\n";
}
int GetNumber(int input) {
int i, num;
int *tmp;
tmp = new int[100];
tmp[0] = 0;
for (i=1;i<100;i++) {
tmp[i] = (input*tmp[i-1]+1)%5;
}
num = tmp[input];
delete[] tmp;
return num;
}
~OtherClass() {
cout << "bye\n";
}
};
class MainClass {
public:
int *myarray;
MainClass(int numcells) {
myarray = new int[numcells];
}
~MainClass() {
delete[] myarray;
}
};
int main() {
int i;
#define NUMELEMS 100
MainClass *mc = new MainClass(NUMELEMS);
OtherClass *oc = new OtherClass();
#pragma omp parallel private(i)
{
#pragma omp for
for (i=0; i<NUMELEMS; i++ ) {
mc->myarray[i] = oc->GetNumber(omp_get_thread_num()+1);
}
} // end of omp parallel
for (i=0; i<NUMELEMS; i++) {
cout << mc->myarray[i] << "\n";
}
delete mc;
delete oc;
}
但它说明了我在处理真实代码时出现的一个问题。即,我想知道OtherClass:GetNumber 中的数组tmp。 tmp 如何填充的细节并不重要;我只是在输入一些代码来生成一些“有趣”的数字,这些数字会因线程而异。我的问题是,tmp 是否充分保护了可能正在运行的各种线程?线程在初始化、访问和删除它时是否可能会相互绊倒?例如,一个线程是否会按照另一个线程的定义访问tmp?或者一个线程可能会在另一个线程可以访问它之前删除tmp?如果需要修改,谁能告诉我应该如何修改代码?
顺便说一句,这段代码运行良好。但我想知道在更复杂、更大的代码中会发生什么。
【问题讨论】:
标签: c++ multithreading openmp