【发布时间】:2021-04-21 21:21:42
【问题描述】:
我被要求用 C 语言编写一个 OpenMP 程序,以便主线程将工作分配给其他线程,当它们在执行任务时,主线程应该定期检查它们是否完成,如果没有,它应该增加一个共享变量。
这是线程任务的函数:
void work_together(int *a, int n, int number, int thread_count) {
# pragma omp parallel for num_threads(thread_count) \
shared(a, n, number) private(i) schedule(static, n/thread_count)
for (long i=0; i<n; i++) {
// do a task, such as:
a[i] = a[i] * number;
}
}
它是从 main 调用的:
int main(int argc, char *argv[]) {
int n = atoi(argv[1]);
int arr[n];
initialize(arr, n);
// this will be the shared variable
int number = 2;
work_together(arr, n, number, thread_count);
//I want to write a function or an if to check whether threads are still working
/* if (threads_still_working()) {
number++;
sleep(100);
}
*/
printf("There are %d threads\n", omp_get_num_threads());
}
thread_count被初始化为4,我尝试对大的n(>10000)执行它,但是主线程会一直等待其他线程完成for循环的执行,并且会只有在work_together() 返回时才继续主线程:printf() 将始终打印只有一个线程在运行。
现在,有什么方法可以从主线程检查其他线程是否仍在运行,如果它们还在运行,则进行一些递增?
【问题讨论】:
标签: c multithreading performance parallel-processing openmp