我有一个类 MainWindow
在 thread
中打开一个 server
函数,我需要共享一个 bool 变量
在我的主线程和我的线程之间,我尝试使用 volatile 变量
但它不起作用,这是代码:
//Constructor
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//Some initialisation
...
// Constructs the new thread and runs it. Does not block execution.
bool_Server = true;//Variable supposed to be shared
m_t1 = std::thread(lancerServeur, bool_Server);
}
MainWindow::~MainWindow()
{
delete ui;
bool_Server = false; //Variable supposed to be shared
m_t1.join();
}
void MainWindow::lancerServeur(bool boolServer){
serveur s;
while(boolServer){
s.receiveDataUDP();//Read data in non blocking mode
}
}
volatile变量是否共享?
最佳答案
您传递的是 bool_Server
的拷贝至 MainWindow::lancerServeur
,因此它观察到的变量与原始 bool_Server
没有任何关系.制作 volatile
不会有帮助,volatile
无论如何都不会访问线程安全的对象。
你应该使用 atomic<bool>
作为标志,并使其成为 MainWindow
的数据成员.无需将其传递给 lancerServeur
.这是一个简单的例子,运行一个线程 5 秒然后退出。
#include <atomic>
#include <thread>
#include <chrono>
#include <iostream>
struct MainWindow
{
std::atomic<bool> stop_{false};
std::thread task_;
void run()
{
while(!stop_) {
std::cout << "Processing ...\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "Stopping ...\n";
}
void launch_thread()
{
task_ = std::thread(&MainWindow::run, this);
}
~MainWindow()
{
stop_ = true;
task_.join();
}
};
int main()
{
{
MainWindow w;
w.launch_thread();
std::this_thread::sleep_for(std::chrono::seconds(5));
}
}
关于c++ - 在主线程之间共享一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24433551/