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

时间:2014-06-26 14:45:21

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

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

是否共享了volatile变量?

2 个答案:

答案 0 :(得分:7)

您已将bool_Server的副本传递给MainWindow::lancerServeur,因此其观察的变量与原始bool_Server没有任何关联。使volatile无法提供帮助,volatile无论如何都无法访问对象的线程安全。

您应该使用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));
  }
}

答案 1 :(得分:2)

在.h文件中,将bool_Server更改为std::atomic<bool> bool_Server并将.cpp文件更改为:

//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, std::ref(bool_Server));

}

MainWindow::~MainWindow()
{
    delete ui;
    bool_Server = false; //Variable supposed to be shared
    m_t1.join();
}


void MainWindow::lancerServeur(std::atomic<bool>& boolServer){
    serveur s;
    while(boolServer){
        s.receiveDataUDP();//Read data in non blocking mode
    }
}