Reputation: 743
I'm trying to design a small program in C. I'm using openMP to parallelise parts of the code, Which reads through a file line by line, stores a number of line reads in an array buffer and calls on a function which for now 'waits' for 10 microseconds. Here's my code. I basically want to execute that particular function in parallel. i.e. the buffer's data is dispatched onto a single thread as soon as it fills up, and then second buffer fills up onto a second thread and so on... . This might not be synchronized, and doesn't need to be at this stage.
int count = 0; //global
char *array_buffer[8]; //global
char process(int lent)
{
int row,col;
#pragma omp single
for(row = 0; row<count; row++)
{
usleep(10);
//printf("%s", array_buffer[row]);
//may be executing another function call from here .... ?
free(array_buffer[row]);
}
return 1;
}
void line(char *line_char)
{
int lent = strlen(line_char);
array_buffer[count] = malloc((lent + 1)*sizeof(char));
strcpy(array_buffer[count], line_char);
#pragma omp parallel
if (count == 8)
{
int returning, returned_all = 0;
returning = process(lent); //function call, waits for 10 microseconds and returns 1 as o/p
#pragma omp single
count = 0;
#pragma omp atomic
returned_all = returned_all + returning;
}
count++;
}
int main(int argc,char **argv)
{
FILE *fp = fopen(argv[1], "r");
if(fp == NULL )
{
printf("Couldn't open file %s",argv[1]);
}
char buff[512];
while (fgets(buff, 512, fp) != NULL )
{
line(buff); /*sending out an array having one line*/
}
return 0;
}
It's obviously not working. I know I have messed up for omp single, but omp atomic seems right. Any help, suggestions or corrections to get this working ?
Upvotes: 0
Views: 1932
Reputation: 22542
I don't even know where to start.
There is just so much wrong with your code.
First: do you know that your parallel code will only run on every 8th row?
if (count == 8)
You allocate returned_all
inside the parallel block, meaning each thread will have it's own private copy of returned_all
.
Your use of #pragma omp single
is completely out of place. Use of this outside of a #omp parallel
block has no effect if it even compiles...
Calling free(array_buffer[row])
inside a parallel function will get you into lot's of trouble with double free's and such.
If you want to process a file line by line in parallel I suggest you make use of the default locking in the stdio library and do something like
#pragma omp parallel
{
// each thread get's it's own private buffer
char buff[512];
while (fgets(buff, 512, fp)) {
// process the line
}
}
Upvotes: 2