并行执行不更新我的变量

Parallel execution doesn't update my variable

本文关键字:变量 我的 更新 并行执行      更新时间:2023-10-16

我想写一个程序,在这个程序中,将创建随机数,并追踪其中最大的一个。两个线程将并行运行。但是,我的best变量停留在它的初始变量。为什么?

[编辑]

我在约阿希姆的回答后更新了代码,但我并不是每次都能得到正确的答案!我错过了什么?

#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex
#include <random>
std::default_random_engine generator((unsigned int)time(0));
int random(int n) {
  std::uniform_int_distribution<int> distribution(0, n);
  return distribution(generator);
}
std::mutex mtx;           // mutex for critical section
void update_cur_best(int& cur_best, int a, int b) {
  // critical section (exclusive access to std::cout signaled by locking mtx):
  mtx.lock();
  if(a > b)
        cur_best = a;
  else
        cur_best = b;
  mtx.unlock();
}
 void run(int max, int& best) {
        for(int i = 0; i < 15; ++i) {
                int a = random(max); int b = random(max);
                update_cur_best(best, a, b);
                mtx.lock();
                std::cout << "|" << a << "| |" << b << "|" << std::endl;
                mtx.unlock();
        }
}
int main ()
{
  int best = 0;
  std::thread th1 (run, 100, std::ref(best));
  std::thread th2 (run, 100, std::ref(best));
  th1.join();
  th2.join();
  std::cout << "best = " << best << std::endl;
  return 0;
}

样本输出:

|4| |21|
|80| |75|
|93| |95|
|4| |28|
|52| |92|
|96| |12|
|83| |8|
|4| |33|
|28| |35|
|59| |52|
|20| |73|
|60| |96|
|61| |34|
|67| |79|
|67| |95|
|54| |57|
|20| |75|
|40| |30|
|16| |32|
|25| |100|
|33| |36|
|69| |26|
|94| |46|
|15| |57|
|50| |68|
|9| |56|
|46| |70|
|65| |65|
|76| |73|
|16| |29|
best = 29

我得了29分,这还不是最高分!

作为更新问题的答案,在update_cur_best中,每次迭代都会覆盖best的值。最后,它的值将只是最近生成的ab对中的较大值。您想要做的是只有当当前ab大于best时才更新它(我不确定为什么每次迭代都会生成两个随机值…)

这是因为你不能真正将引用传递给线程构造函数,因为它们不会作为引用传递,而是被复制,而正是这些副本被传递给你的线程函数。您必须使用std::ref来包装引用。

例如

std::thread th1 (run, 100, std::ref(best));