gpt4 book ai didi

c - 了解 OpenMP 有关 fork 的缺点

转载 作者:行者123 更新时间:2023-12-02 09:14:20 28 4
gpt4 key购买 nike

我想了解它们在这里的含义。为什么这个程序会“挂起”?

来自https://bisqwit.iki.fi/story/howto/openmp/

OpenMP and fork() It is worth mentioning that using OpenMP in a program that calls fork() requires special consideration. This problem only affects GCC; ICC is not affected. If your program intends to become a background process using daemonize() or other similar means, you must not use the OpenMP features before the fork. After OpenMP features are utilized, a fork is only allowed if the child process does not use OpenMP features, or it does so as a completely new process (such as after exec()).

This is an example of an erroneous program:

#include <stdio.h>   
#include <sys/wait.h>
#include <unistd.h>

void a(){
#pragma omp parallel num_threads(2)
{
puts("para_a"); // output twice
}
puts("a ended"); // output once
}

void b(){
#pragma omp parallel num_threads(2)
{
puts("para_b");
}
puts("b ended");
}

int main(){
a(); // Invokes OpenMP features (parent process)
int p = fork();
if(!p){
b(); // ERROR: Uses OpenMP again, but in child process
_exit(0);
}
wait(NULL);
return 0;
}

When run, this program hangs, never reaching the line that outputs "b ended". There is currently no workaround as the libgomp API does not specify functions that can be used to prepare for a call to fork().

最佳答案

发布的代码违反了 POSIX 标准。

POSIX fork() standard states :

A process shall be created with a single thread. If a multi-threaded process calls fork(), the new process shall contain a replica of the calling thread and its entire address space, possibly including the states of mutexes and other resources. Consequently, to avoid errors, the child process may only execute async-signal-safe operations until such time as one of the exec functions is called.

运行 OMP 并行化代码显然违反了上述限制。

关于c - 了解 OpenMP 有关 fork 的缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49049388/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com