OpenMP 4.5任务依赖未按预期生效,执行顺序异常求助
Let's break down what's happening here and fix your issue.
First, the core misunderstanding is in how OpenMP's depend clauses interact with task submission order.
Why Your Current Code Fails
OpenMP task dependencies are built between tasks as they are submitted. When you submit the task with depend(in:x) first, there are no existing tasks with depend(out:x) that it needs to wait on—because that write task hasn't been created yet. So the runtime schedules the read task immediately. Then when you submit the depend(out:x) task, it runs after the first one, which gives you the reversed output you're seeing.
The depend(in:x) clause tells the runtime: "This task reads x, so wait for all previously submitted tasks that wrote x (via depend(out:x) or depend(inout:x)) to finish before running me." It doesn't look ahead to tasks you'll submit later.
The Fix: Reorder Your Tasks
To get the expected order, you need to submit the write task first (the one with depend(out:x)), then the read task (with depend(in:x)). This way, when the read task is submitted, it sees the prior write task and waits for it to complete.
Here's the corrected code:
#include <iostream> using namespace std; int main() { int x=0; #pragma omp parallel #pragma omp single { // Submit write task first #pragma omp task depend(out:x) { x = 3; #pragma omp critical cout << "Set the value to " << x << "\n"; } // Now submit read task, which depends on the prior write task #pragma omp task depend(in:x) { #pragma omp critical cout << "Read the value " << x << "\n"; } } return 0; }
Why This Works
- The
depend(out:x)task is submitted first, marking that it will modifyx. - When the
depend(in:x)task is submitted next, the runtime recognizes that it needs to readx, so it waits for the earlier write task to finish before executing the read task.
Compiling this with g++-7 -fopenmp your_file.cpp will produce your expected output:
Set the value to 3 Read the value 3
A Quick Note on g++ 7.3.1
Your compiler version does support OpenMP 4.5, so task dependencies are implemented correctly here—this wasn't a compiler issue, just a misunderstanding of how dependency relationships are established based on submission order.
内容的提问来源于stack exchange,提问作者ender46

