本文介绍了两个线程使用同一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个线程:'main' 和 'worker',还有一个全局变量 bool isQuitRequested 将被 main 线程用来通知 worker,什么时候退出它的 while 循环(类似这样:while(isQuitRequested == false) { ... 做一些事情 ... })

I have two threads: 'main' and 'worker', and one global variable bool isQuitRequested that will be used by the main thread to inform worker, when it's time to quit its while loop (something like this: while(isQuitRequested == false) { ... do some stuff ... })

现在,我有点担心...我是否需要对 isQuitRequested 使用某种互斥保护,考虑到只有一个线程 (main) 执行 isQuitRequested = true 操作,并且其他 (worker) 只执行检查而不执行其他操作?

Now, I'm a bit concerned...Do I need to use some kind of mutex protection for isQuitRequested, considering that only one thread (main) performs isQuitRequested = true operation, and the other (worker) just performs checking and nothing else?

我已阅读 如果两个线程同时访问同一个 bool 变量会发生什么?.我不是类似的东西,但不一样的情况...

I have read What could happen if two threads access the same bool variable at the same time?.I'ts something similar, but not the same situation...

推荐答案

您没有指定您使用的是哪种语言,并且从您发布的小代码片段来看,它可以是 C#、Java 或 C++.以下是针对每个模式"的一些常见解决方案:

You have not specified which language you are using and from the small code snippet that you posted it could be either C#, Java or C++. Here are some common solutions for this "pattern" for each of them:

C#:

volatile bool isQuitRequested;

Java:

volatile boolean isQuitRequested;

C++:volatile 在 C++ 中几乎没有那么有用.一起去:

C++: volatile in C++ is not nearly as useful. Go with:

std::atomic<bool> isQuitRequested;

这篇关于两个线程使用同一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 09:21