TL; DR:你没有。
我需要两个线程(主线程(GUI)和计算线程)之间的共享接口。 (重点煤矿)
QSharedMemory
才有意义,多处理,不支持多线程。线程的整体思路是,他们喜欢的过程,但共享的过程中,他们都在内存中所有。
因此,所有的线程看到提供给您的进程的内存中的所有和你根本不需要做任何事情来分享它。
你需要找出计算线程是否应该是:
只有更新与主线程,或
通报的变化的主线程共享的数据结构,其通过提供改变的键值对,或
两者。
与更新的数据结构的问题是,除非你也提供变化的通知,主线程将别无选择,只能轮询结构变化。因此,现在你在主线程上运行了一些代码,但这些代码并没有太多的功能,但它运行在一个计时器上,并强制CPU唤醒,并使你的移动和虚拟化用户憎恨你。不太好。
由于到共享数据结构的任何访问都必须通过一个互斥体,以便读者是不读的胡言乱语而作家更新的价值得到保护,这是给你做出抉择:
饲养只有计算线程中的数据结构的一个副本,并在互斥保护下访问它。主线程和计算线程将争夺该互斥量,性能将受到影响。
保留数据结构的两个副本 - 一个在计算线程中,另一个在任何希望跟踪计算进度的线程中。
保留一个无锁数据结构的副本。
下面,我演示了如何在计算和主线程中保留一个单独的数据结构。我还利用Model-View和一个标准模型来为计算引擎提供UI。
计算机的实现被拆分为一个抽象基类和特定于您的计算问题的具体实现。所有具体的类需要做的是实现两种方法:一种计算一个模拟时间步长,返回其长度,另一个通知其用户数据变化。
Computer
对象提供对其数据的随机更新,“模拟”随机持续时间的时间步长。通过随机选择一个时间步长的1/4的时间进行睡眠,它会阻塞随机时间。因此,它就好像它可以计算比实时快4倍的数据。
AbstractComputer
采用这个简单的功能,并建立在它的基础上,提供四种操作模式:单步,实时和快速。
根据模拟的时间推移,在一个块中由computeChunk
执行的计算量被设置为m_notifyPeriod
,这里设置为20ms。
在除Stop
以外的所有操作模式中,在将控制权返回给事件循环以保持计算线程响应之前,始终计算至少单个块。单个计时器用于将控制从事件循环返回到计算机并计划未来的计算。在实时模式下,如果计算超前于实时时钟,则会在适当的时刻安排下一次计算,以便实时运行。在快速模式下,定时器设置为零超时,立即从事件循环返回控制以执行另一个计算组块。这具有非常低的开销。
抽象计算机跟踪累计的模拟时间步(simTime
)。
计算机对象在其自己的线程中运行并为其数据提供周期性的随机生成的更新。数据更改通过通知信号指示。更新后的数据被插入到UI对象的标准模型中。链接两个对象的信号插槽连接是排队类型 - newValue
插槽调用发生在主线程中。
下拉组合具有焦点,所以您只需单步操作就可以按住↓(向下箭头键)。
请注意,AbstractComputer
的实施以不会阻止比m_notifyPeriod
中的较大值或一个模拟步骤(一次调用compute
)更长的方式来完成。在单核机器上,将Computer
实例移至另一个线程实际上会降低性能!执行main
是为了考虑到这一点。
最后,作为性能优化,您应该在(可选)排序的字符串表中使用string interning,并将该表(a.k.a. atoms)中的索引用作参数键,而不是原始字符串。
#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"
我的 “乱语” 字典确实包括三个项目,非常感谢你:)
这是复杂的问题。用两个字:你需要使用写和使用你自己的分配器(对于QHash,QString和double),这将使用共享内存缓冲区。但我建议你看一下boost进程容器。 –
在您的特定情况下它可能不实用,但是如果是这样的话,如果您可以对信号进行排序,则会更容易。如果所有访问线程/进程都会看到相同的'Signalname'值,他们可以'std :: sort'它们并使用'std :: binary_search'获取数组索引 - 然后将共享内存视为一个' double's。 –
真的需要SharedMemory吗? SharedMemory用于进程之间的通信。对于同一进程内的线程之间的通信,只要所有访问都正确同步,数据可以更容易地共享为全局变量或堆。 –