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

标签 c++ multithreading qt c++11 network-programming

我有一个类 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/

相关文章:

c++ - 我什么时候调用 boost::asio::streambuf::consume() 和 boost::asio::streambuf::commit()?

C++ 二进制表达式树 : How do I print an infix expression with appropriate parentheses?

ios - CLLocationManager didUpdateToLocation :, 在哪个线程上?

qt - qml 虚拟键盘 : keyboardDesignWidth and Height

c++ - 如何使用 Qt QGraphicsitem 设计轴

c++ - VS2010中MFC模板项目的问题

c++ - 如何在 C++ 中使函数异步?

c - 关于Getcontext函数的问题

objective-c - self 释放后

c++ - 使用 wkhtmltopdf C 库将本地 HTML 文件转换为 PDF