gpt4 book ai didi

c++ - 在主线程之间共享一个变量

转载 作者:太空狗 更新时间:2023-10-29 19:58:13 25 4
gpt4 key购买 nike

我有一个类 MainWindowthread 中打开一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com