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用於進程之間的通信。對於同一進程內的線程之間的通信,只要所有訪問都正確同步,數據可以更容易地共享爲全局變量或堆。 –