小编Cow*_*Man的帖子

任务完成后复制 OpenMP 整数

我不知道这是否在任何地方都有记录,如果有,我希望引用它,但是我在使用 OpenMP 时发现了一些意外的行为。我下面有一个简单的程序来说明这个问题。在这里,我将以点的形式讲述我期望该程序执行的操作:

  • 我想要 2 个线程
  • 他们都共享一个整数
  • 第一个线程递增整数
  • 第二个线程读取整数
  • 递增一次后,外部进程必须告诉第一个线程继续递增(通过互斥锁)
  • 第二个线程负责解锁该互斥体

正如您将看到的,线程之间共享的计数器对于第二个线程没有正确更改。但是,如果我将计数器转换为整数引用,我会得到预期的结果。这是一个简单的代码示例:

#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)

c++ multithreading gcc mutex openmp

1
推荐指数
1
解决办法
61
查看次数

标签 统计

c++ ×1

gcc ×1

multithreading ×1

mutex ×1

openmp ×1