如何在 C 中对多个文件 reading/writing 操作使用多个线程?
How to use multiple threads for multiple file reading/writing operations in C?
我正在尝试分析对多个文件执行大文件 reading/writing 操作所需的最佳线程数。
那么我如何继续创建多个线程并为每个线程分配一定数量的文件以加快执行时间呢?
使用的语言- C
查看 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;
}
我正在尝试分析对多个文件执行大文件 reading/writing 操作所需的最佳线程数。 那么我如何继续创建多个线程并为每个线程分配一定数量的文件以加快执行时间呢? 使用的语言- C
查看 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;
}