如何从计算线程获取结果到GUI线程 - 我需要QSharedMemory吗?

时间:2015-08-24 09:16:49

标签: c++ qt

我需要两个线程(主线程(GUI)和计算线程)之间的共享接口。在启动期间,主线程将所有信号存储在QHash(<QString Signalname, double value>)中。第二个线程在每个计算步骤中写入键/值。我应该将它们存储在QSharedMemory吗?

我的应用程序有两个主题。 GUI线程和Compute线程。用户可以通过GUI以快速模式或实时模式启动模拟。计算通过时间演化模拟模型。它们足够快,可以比实时更快地执行。如果您插入延迟,可以将它们保持在实时速度,就像您所做的那样。在游戏或动画中。

Compute线程应该以四种模式之一执行计算:

  1. 快速模式:计算无延迟地完成,并且比实时更快地演化模型。这是在使用while (...) { ... run_ComputeFunction()... }

  2. 的线程运行中实现的
  3. 实时模式:这是在使用QTimer超时和广告位run_ComputeFunction()的线程运行中实现的。

  4. 单步模式:用户启动GUI的每个时间步。这类似于在调试器中单步执行。这是在使用start thread而不是run_ComputeFunction的线程运行中实现的,而不是等待条件。

  5. 停止模式:计算已停止。

2 个答案:

答案 0 :(得分:4)

TL; DR:你没有。

  

我需要两个线程(主线程(GUI)和计算线程)之间的共享接口。 (强调我的)

QSharedMemory仅适用于多处理,而非多线程。线程的整个想法是它们就像进程一样,但是共享它们所处的进程的所有内存。

因此,您的所有主题都会看到您的进程可用的所有内存,并且您根本不需要做任何事情来共享它。

你需要弄清楚计算线程是否应该是:

  1. 仅更新与主线程共享的数据结构

  2. 通过提供已更改的键值对

  3. ,通知主线程状态发生变化
  4. 两个

  5. 更新数据结构的问题在于,除非提供更改通知,否则主线程将别无选择,只能轮询结构以进行更改。因此,现在您在主线程上运行一些代码并没有做太多的代码,但是在定时器上运行并强制CPU唤醒并使您的移动和虚拟化用户讨厌您。不太好。

    由于对共享数据结构的任何访问必须受到互斥锁的保护,以便读者在编写器更新值时不会读取乱码,因此由您决定:

    1. 在计算线程中只保留一个数据结构副本,并在互斥保护下访问它。主要和计算线程将竞争该互斥体,性能将受到影响。

    2. 保留数据结构的两个副本 - 一个在计算线程上,另一个在任何希望跟踪计算进度的线程中。

    3. 保留一个无锁数据结构的副本。

    4. 下面,我将演示如何在计算主线程和主线程中保留单独的数据结构。我还利用模型视图和标准模型为计算引擎提供UI。

      计算机的实现分为抽象基类和特定于计算问题的具体实现。具体类需要做的就是实现两个方法:一个用于计算一个模拟时间步长,返回其长度,另一个用于向用户通知数据的更改。

      Computer对象提供对其数据的随机更新,&#34;模拟&#34;随机持续时间的时间步长。它通过在随机选择的时间步长的持续时间内休眠1/4来阻止随机时间量。因此,它似乎可以比实时更快地计算数据4倍。

      AbstractComputer采用这个简单的功能,并以此为基础提供四种操作模式:单步,实时和快速。

      根据模拟时间推移,computeChunk在一个块中执行的计算量设置为m_notifyPeriod,此处设置为20毫秒。

      Stop以外的所有操作模式中,在将控制返回到事件循环之前,始终至少计算单个块以保持计算线程的响应。单个计时器用于将控制从事件循环返回到计算机并安排将来的计算。在实时模式中,如果计算在实时时钟之前,则在适当的时刻安排下一次计算,以使其实时运行。在快速模式下,定时器设置为零超时,立即从事件循环返回控制以执行另一个计算块。这开销非常低。

      抽象计算机跟踪累积的模拟时间步长(simTime)。

      计算机对象在其自己的线程中运行,并为其数据提供定期的,随机生成的更新。通过通知信号指示对数据的改变。更新的数据将插入UI对象的标准模型中。链接两个对象的信号槽连接是排队类型 - newValue槽调用发生在主线程中。

      下拉组合具有焦点,因此您需要执行的单步操作是按住(向下箭头键)。

      请注意AbstractComputer的实施方式是这样做的,即不要阻止比m_notifyPeriod或一个模拟步骤(一次调用compute)更长的时间。在单核机器上,将Computer实例移动到另一个线程实际上会降低性能!实施main是为了考虑到这一点。

      最后,作为性能优化,您应该在(可选地排序的)字符串表中使用string interning并使用此表(a.k.a。atoms)中的索引作为参数键,而不是原始字符串。

      screenshot

      #include <QtWidgets>
      #include <random>
      
      class AbstractComputer : public QObject {
         Q_OBJECT
         Q_PROPERTY (Mode mode READ mode WRITE setMode NOTIFY modeChanged)
         Q_PROPERTY (double simTime READ simTime WRITE setSimTime
                     RESET resetSimTime NOTIFY simTimeChanged)
      public:
         enum Mode { Stop, Step, RealTime, Fast };
      protected:
         typedef double Time; ///< units of seconds
      
         /// Performs one computation step and returns the amount of time the simulation has
         /// been advanced by. The computation updates one or more parameters in the map, but
         /// doesn't signal the updates. The changed parameters are kept in set.
         /// This method can change m_mode to Stop to direct the calling code to stop/pause
         /// the simulation.
         virtual Time compute() = 0;
      
         /// Notifies of accumulated changes and clears the update set.
         virtual void notify() = 0 ;
      private:
         Mode m_mode, m_prevMode;
         QBasicTimer m_timer;
         QElapsedTimer m_timeBase;
         qint64 m_lastNotification; ///< Last m_timeBase at which notification was issued.
         Time m_notifyPeriod; ///< Real time period to issue data change notifications at.
         Time m_modeSimTime;  ///< Simulation time accumulated in current mode.
         Time m_simTime;      ///< Total simulation time.
      
         /// Computes a chunk of work that amounts to m_notifyPeriod in simulated time
         void computeChunk() {
            Time t = 0;
            do
               t += compute();
            while (m_mode != Stop && t < m_notifyPeriod);
            m_modeSimTime += t;
            m_simTime += t;
         }
      
         /// Runs computations according to the selected mode. In RealTime and Fast modes,
         /// the notifications are issued at least every m_notifyPeriod.
         void timerEvent(QTimerEvent * ev) {
            if (ev->timerId() != m_timer.timerId()) return;
            const Time startSimTime = m_simTime;
            const Mode startMode = m_mode;
            switch (m_mode) {
            case Step:
               m_simTime += compute();
               m_timer.stop();
               m_mode = Stop;
               break;
            case Stop:
               m_timer.stop();
               break;
            case RealTime:
               if (m_prevMode != RealTime) {
                  m_modeSimTime = 0.0;
                  m_timeBase.start();
               }
               computeChunk();
               if (m_mode == RealTime) {
                  int ahead = round(m_modeSimTime * 1000.0 - m_timeBase.elapsed());
                  if (ahead < 0) ahead = 0;
                  m_timer.start(ahead, Qt::PreciseTimer, this);
               }
               break;
            case Fast:
               if (m_prevMode != Fast) {
                  m_timeBase.start();
                  m_lastNotification = 0;
               }
               do
                  computeChunk();
               while (m_mode == Fast
                      && ((m_timeBase.elapsed() - m_lastNotification) < m_notifyPeriod*1000.0));
               m_lastNotification = m_timeBase.elapsed();
               break;
            }
            notify();
            if (startSimTime != m_simTime) emit simTimeChanged(m_simTime);
            if (m_prevMode != m_mode || startMode != m_mode) emit modeChanged(m_mode);
            m_prevMode = m_mode;
         }
      public:
         AbstractComputer(QObject * parent = 0) :
            QObject(parent), m_mode(Stop), m_prevMode(Stop), m_notifyPeriod(0.02) /* 50 Hz */,
            m_simTime(0.0)
         {}
         Q_SIGNAL void modeChanged(AbstractComputer::Mode mode); // fully qualified type is required by moc
         Q_SIGNAL void simTimeChanged(double);
         Q_SLOT void setMode(AbstractComputer::Mode mode) { // fully qualified type is required by moc
            if (m_mode == mode) return;
            m_mode = mode;
            if (m_mode != Stop) m_timer.start(0, this); else m_timer.stop();
         }
         Q_SLOT void stop() { setMode(Stop); }
         Mode mode() const { return m_mode; }
         double simTime() const { return m_simTime; }
         void setSimTime(double t) { if (m_simTime != t) { m_simTime = t; emit simTimeChanged(t); } }
         void resetSimTime() { setSimTime(0.0); }
      };
      Q_DECLARE_METATYPE(AbstractComputer::Mode)
      
      class Computer : public AbstractComputer {
         Q_OBJECT
      public:
         typedef QHash<QString, double> Map;
      private:
         typedef QSet<QString> Set;
         std::default_random_engine m_eng;
         Map m_data;
         Set m_updates;
      
         Time compute() Q_DECL_OVERRIDE {
            // Update one randomly selected parameter.
            auto n = std::uniform_int_distribution<int>(0, m_data.size()-1)(m_eng);
            auto it = m_data.begin();
            std::advance(it, n);
            auto val = std::normal_distribution<double>()(m_eng);
            *it = val;
            m_updates.insert(it.key());
            float tau = std::uniform_real_distribution<float>(0.001, 0.1)(m_eng);
            // Pretend that we run ~4x faster than real time
            QThread::usleep(tau*1E6/4.0);
            return tau;
         }
         void notify() Q_DECL_OVERRIDE {
            for (auto param : m_updates)
               emit valueChanged(param, m_data[param]);
            m_updates.clear();
         }
      public:
         Computer(const Map & data, QObject * parent = 0) :
            AbstractComputer(parent), m_data(data) {}
         Map data() const { return m_data; }
         Q_SIGNAL void valueChanged(const QString & key, double val);
      };
      
      class UI : public QWidget {
         Q_OBJECT
         QHash<QString, int> m_row;
         QStandardItemModel m_model;
         QFormLayout m_layout { this };
         QTableView m_view;
         QComboBox m_mode;
      public:
         UI(const Computer * computer, QWidget * parent = 0) :
            QWidget(parent),
            m_model(computer->data().size() + 1, 2, this)
         {
            auto data = computer->data();
            m_mode.addItem("Stop", Computer::Stop);
            m_mode.addItem("Step", Computer::Step);
            m_mode.addItem("Real Time", Computer::RealTime);
            m_mode.addItem("Fast", Computer::Fast);
            m_mode.setFocusPolicy(Qt::StrongFocus);
            m_view.setFocusPolicy(Qt::NoFocus);
            m_layout.addRow(&m_view);
            m_layout.addRow("Sim Mode", &m_mode);
            m_model.setItem(0, 0, new QStandardItem("Sim Time [s]"));
            m_model.setItem(0, 1, new QStandardItem);
            int row = 1;
            for (auto it = data.begin(); it != data.end(); ++it) {
               m_model.setItem(row, 0, new QStandardItem(it.key()));
               m_model.setItem(row, 1, new QStandardItem(QString::number(it.value())));
               m_row[it.key()] = row++;
            }
            newMode(computer->mode());
            newSimTime(computer->simTime());
            m_view.setModel(&m_model);
            connect(&m_mode, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
                    [this](int i){
               emit modeChanged((AbstractComputer::Mode)m_mode.itemData(i).toInt());
            });
         }
         Q_SIGNAL void modeChanged(AbstractComputer::Mode);
         Q_SLOT void newValue(const QString & key, double val) {
            m_model.item(m_row[key], 1)->setText(QString::number(val));
         }
         Q_SLOT void newSimTime(double t) {
            m_model.item(0, 1)->setText(QString::number(t));
         }
         Q_SLOT void newMode(AbstractComputer::Mode mode) {
            m_mode.setCurrentIndex(m_mode.findData(mode));
         }
      };
      
      struct Thread : public QThread { ~Thread() { quit(); wait(); } };
      
      int main(int argc, char *argv[])
      {
         QApplication a(argc, argv);
         qRegisterMetaType<AbstractComputer::Mode>();
         Computer::Map init;
         init.insert("Foo", 1);
         init.insert("Bar", 2);
         init.insert("Baz", 3);
         Computer computer(init);
         QScopedPointer<Thread> thread;
         UI ui(&computer);
         QObject::connect(&computer, &Computer::valueChanged, &ui, &UI::newValue);
         QObject::connect(&computer, &Computer::simTimeChanged, &ui, &UI::newSimTime);
         QObject::connect(&computer, &Computer::modeChanged, &ui, &UI::newMode);
         QObject::connect(&ui, &UI::modeChanged, &computer, &Computer::setMode);
         int threadCount = Thread::idealThreadCount();
         if (threadCount == -1 || threadCount > 1) { // Assume a multicore machine
            thread.reset(new Thread);
            computer.moveToThread(thread.data());
            thread->start();
            // Prevent the bogus "QBasicTimer::stop: Failed." warnings.
            QObject::connect(thread.data(), &QThread::finished, &computer, &Computer::stop);
         }
         ui.show();
         return a.exec();
      }
      
      #include "main.moc"
      

      我的&#34;随机词&#34;字典 包含三个项目,非常感谢:)

答案 1 :(得分:1)

如果你还没有碰到它,Qt提供了一个QSharedMemory示例,可以让你开始朝着正确的方向前进:http://doc.qt.io/qt-5/qtcore-ipc-sharedmemory-example.html

QThread文档也会有所帮助:http://doc.qt.io/qt-5/qthread.html

如果您仍然遇到困难,可以随时使用最少的代码示例更新您的问题。