Reputation: 304
I remembered to have some trouble with OpenMp and writing into files in parallel, therefore I wrote a simple testprogram that creates files for every for iteration and counts down to zero in the file. Surprisingly it seems to work! If I open the taskmanager with top, I see always just one cpu with a load around 90% and the others around 1%-5%. Is it because the task is not cpu heavy or is there something going wrong (sometimes 2-3 cpus go up to 40%)?
The Testprogram
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<omp.h>
void print2file(char filename[],int i){
FILE *fp;
int j;
fp=fopen(strcat(filename,".txt"),"w");
for(j=i;j>=0;j--)
fprintf(fp,"%d\n",j);
fclose(fp);
}
int main(){
int i;
char test[12];
#pragma omp for
for(i=0;i<1000000000;i++){
sprintf(test,"%d",i);
//printf("test %d",i);
print2file(test,i);
}
}
Upvotes: 0
Views: 64
Reputation: 23497
#pragma omp for
need to be in a parallel region. Either use #pragma omp parallel
followed by #pragma omp for
inside, or a shortcut #pragma omp parallel for
.
Note that you need i
and test
to be thread-local variables, not shared ones, to prevent data race. There are many ways how to achieve this, such as declaring these variables inside a parallel region, make them private
/firstprivate
in an OpenMP clause, make them threadprivate
, etc.
Upvotes: 2