首页 文章

使用openmp并行函数调用

提问于
浏览
0

我正在尝试在C中设计一个小程序 . 我正在使用openMP来并行部分代码,它逐行读取文件,在数组缓冲区中存储多个行读取并调用一个函数,用于现在'等待'10微秒 . 这是我的代码 . 我基本上想要并行执行该特定功能 . 即缓冲区的数据一填满就被分派到一个线程上,然后第二个缓冲区填满第二个线程,依此类推....这可能不同步,并且不需要处于此阶段 .

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;
}

这显然不起作用 . 我知道我已经搞砸了omp单身,但omp原子似乎是正确的 . 任何帮助,建议或更正,以使这项工作?

1 回答

  • 2

    我甚至不知道从哪里开始 .

    你的代码有很多错误 .

    第一:你知道你的并行代码只会在每第8行运行吗?

    if (count == 8)
    

    您在并行块内部分配 returned_all ,这意味着每个线程将拥有它自己的 returned_all 的私有副本 .

    您对 #pragma omp single 的使用完全不合适 . 如果它甚至可以编译,那么在 #omp parallel 块之外使用它是没有效果的......

    在并行函数中调用 free(array_buffer[row]) 会让你进入很多's of trouble with double free'等等 .

    如果你想并行处理一个文件我建议你使用stdio库中的默认锁定并做类似的事情

    #pragma omp parallel
    {
        // each thread get's it's own private buffer
        char buff[512];
        while (fgets(buff, 512, fp)) {
            // process the line
        }
    }
    

相关问题