在main和thread之间共享一个变量

Eva*_*eil 3 c++ qt multithreading network-programming c++11

我有一个在a MainWindow中打开一个server函数的类thread,我需要bool variable在我的主线程和我的线程之间共享一个,我尝试使用volatile variable但它不起作用,这里是代码:

//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
    }
}
Run Code Online (Sandbox Code Playgroud)

volatile变量是否共享?

Pra*_*ian 7

您传递的是副本,因此它观察bool_ServerMainWindow::lancerServeur的变量与原始变量没有任何关联bool_Server.使它volatile无济于事,并且volatile无论如何也无法访问对象的线程安全.

您应该使用an atomic<bool>作为标志,并使其成为数据成员MainWindow.没有必要把它传递给lancerServeur.这是一个运行5s的线程然后退出的简单示例.

#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));
  }
}
Run Code Online (Sandbox Code Playgroud)