如何在C中使用多个线程进行多个文件读/写操作?

时间:2019-02-18 08:02:06

标签: multithreading pthreads file-handling

我正在尝试分析对多个文件执行大文件读取/写入操作所需的最佳线程数。 那么,如何继续创建多个线程并为每个线程分配一定数量的文件以加快执行时间呢? 使用的语言-C

1 个答案:

答案 0 :(得分:0)

使用https://en.wikipedia.org/wiki/OpenMP创建线程并有效地管理它们以进行分析。

在这种情况下,您要做的是使用多个单线程并将工作负载分配给它们或一组线程,这些线程将获得相等的工作份额。以下示例:

int main(int argc, char **argv)
{
    // split work in sections
    #pragma omp parallel sections
    {    
        #pragma omp section
        {
            function_1(); // where you perform R/W operations
        }

        #pragma omp section
        {
            function_2(); // where you perform R/W operations or other
        }
    }

    // split work on N threads equally
    #pragma omp parallel
    {
        // where you perform R/W operations
    }
    int threadNum = omp_get_thread_num();
    printf("Number of threads used: %d\n",threadNum);

    /*
    example for loop: if you have 2 threads this work would be split with
    i that runs from 0 to 49999 while the second gets a version running from 50000 to 99999.
    */
    int arr[100000];
    #pragma omp parallel for  
    {
        for (int i = 0; i < 100000; i++) {
          arr[i] = 2 * i;
        }
    }
    int threadNum = omp_get_thread_num();
    printf("Number of threads used: %d\n",threadNum);

    return 0;
}