我不知道这是否在任何地方都有记录,如果有,我希望引用它,但是我在使用 OpenMP 时发现了一些意外的行为。我下面有一个简单的程序来说明这个问题。在这里,我将以点的形式讲述我期望该程序执行的操作:
正如您将看到的,线程之间共享的计数器对于第二个线程没有正确更改。但是,如果我将计数器转换为整数引用,我会得到预期的结果。这是一个简单的代码示例:
#include <mutex>
#include <thread>
#include <chrono>
#include <iostream>
#include <omp.h>
using namespace std;
using std::this_thread::sleep_for;
using std::chrono::milliseconds;
const int sleep_amount = 2000;
int main() {
int counter = 0; // if I comment this and uncomment the 2 lines below, I get the expected results
/* int c = 0; */
/* int &counter = c; */
omp_lock_t mut;
omp_init_lock(&mut);
int counter_1, counter_2;
#pragma omp parallel
#pragma omp …Run Code Online (Sandbox Code Playgroud)