我正在用 Qt/C++ 开发一个应用程序。在某些时候,有两个线程:一个是 UI 线程,另一个是后台线程。我必须根据类型为 bool
的外部变量的值从后台线程执行一些操作。我通过单击 UI 上的按钮来设置此值。
header.cpp
extern bool globalVar;
主窗口.cpp
//main ui thread on button click
setVale(bool val){
globalVar = val;
}
backgroundThread.cpp
while(1){
if(globalVar)
//do some operation
else
//do some other operation
}
在这里,写入 globalVar
仅在用户单击按钮时发生,而读取是连续发生的。
所以我的问题是:
- 在上述情况下,是否必须使用互斥锁?
- 如果读取和写入同时发生,这会导致应用程序崩溃吗?
- 如果读取和写入同时发生,
globalVar
是否会具有除true
或false
之外的其他值? - 最后,操作系统是否提供任何类型的锁定机制来防止读/写操作由不同的线程同时访问内存位置?
最佳答案
循环
while(1){
if(globalVar)
//do some operation
else
//do some other operation
}
是busy waiting ,这是非常浪费的。因此,您最好使用一些经典的同步,它会在有事情要做时唤醒后台线程(主要是)。你应该考虑改编 this example of std::condition_variable
.
假设您从:
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex m;
std::condition_variable cv;
bool ready = false;
你的工作线程可以是这样的:
void worker_thread()
{
while(true)
{
// Wait until main() sends data
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return ready;});
ready = false;
lk.unlock();
}
通知线程应该做这样的事情:
{
std::lock_guard<std::mutex> lk(m);
ready = true;
}
cv.notify_one();
关于c++ - 从不同的线程访问外部变量是否必须使用互斥锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36287171/