并行执行不更新我的变量
Parallel execution doesn't update my variable
我想写一个程序,在这个程序中,将创建随机数,并追踪其中最大的一个。两个线程将并行运行。但是,我的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
的值。最后,它的值将只是最近生成的a
、b
对中的较大值。您想要做的是只有当当前a
或b
大于best
时才更新它(我不确定为什么每次迭代都会生成两个随机值…)
这是因为你不能真正将引用传递给线程构造函数,因为它们不会作为引用传递,而是被复制,而正是这些副本被传递给你的线程函数。您必须使用std::ref
来包装引用。
例如
std::thread th1 (run, 100, std::ref(best));
相关文章:
- 为什么我的变量没有更新,我的 LED 没有亮起?
- 为什么我的变量存在于其范围之外
- 为什么我的字符串变量没有打印完整的字符串?
- 为什么我的 c++ 程序检查不是初始化的变量?
- 为什么我的全局变量似乎没有变化?
- C ++程序如何返回我的数组或写入全局变量
- 为什么我的数组值与此处的全局变量不匹配?
- 为什么弹出我的堆栈会返回垃圾而不是初始变量?
- 我的包装函数缺少变量?
- 在我的变量打印C++后无法获得 $ 打印符号
- 我的 c++ 程序似乎没有发现字符串和我拥有但输入使用 getline 的变量之间的比较
- 为什么我的双变量通过添加 c++ 显示 nan?
- 我应该使我的局部变量常量还是可移动的
- constexpr 函数在编译时获取值,即使我的变量不是 constexpr
- 我可以在我的类中使用 omnetpp.ini 变量吗?
- 我的类中应该有一个Allocator作为成员变量吗
- 我可以在初始化之前使用 std::array 成员变量中的 data() 指针吗?发出警告
- 为什么我的 std::atomic<int> 变量不是线程安全的?
- 为什么访问我的引用捕获变量会导致我的 lambda 函数出现段错误?
- 为什么我的程序没有更改结构变量中的值?