The following toy code does nothing useful that I am aware of:
#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;
}
But it illustrates a question that has arisen in my mind while dealing with a real code. Namely, I am wondering about the array tmp in OtherClass:GetNumber. The details of how tmp is populated are unimportant; I was just putting in some code to produce some "interesting" numbers that would somehow vary from thread to thread. My question is, is tmp adequately protected from the various threads that might be running? Is it possible that the threads will be tripping over each other as they initialize, access, and delete it? Will one thread access tmp as defined by another thread, for instance? Or might one thread delete tmp before another thread can access it? Can someone tell me how I should modify the code, if modifications are needed?
This code runs fine by the way. But I am wondering what might happen in a much more complicated, larger code.