Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //mainwindow.h
- #ifndef MAINWINDOW_H
- #define MAINWINDOW_H
- #include <thread>
- #include <mutex>
- #include <QMainWindow>
- namespace Ui { class MainWindow; }
- struct Observer
- {
- virtual void notify() = 0;
- };
- class Core
- {
- public:
- void *run()
- {
- std::thread thread(&Core::runP, this);
- thread.detach();
- }
- void setObserver(Observer *observer) { _observer = observer; }
- int ii() const { return _ii; }
- void nextIi() { _ii++; }
- void lock() { _mutex.lock(); }
- bool tryLock() { return _mutex.try_lock(); }
- void unlock() { _mutex.unlock(); }
- private:
- void runP()
- {
- for (int i = 1; i <= 1000; i++) {
- if (i % 10 == 0) {
- lock();
- nextIi();
- unlock();
- notify();
- }
- }
- }
- void notify() { _observer->notify(); }
- Observer *_observer;
- int _ii;
- std::mutex _mutex;
- };
- struct MwObserver : public QObject, public Observer
- {
- Q_OBJECT
- public:
- explicit MwObserver(struct MainWindow *mainWindow) { _mainWindow = mainWindow; }
- virtual void notify() { emit SomeEvent(); }
- signals:
- void SomeEvent();
- public:
- MainWindow *_mainWindow;
- };
- class MainWindow : public QMainWindow
- {
- Q_OBJECT
- public:
- explicit MainWindow(QWidget *parent = 0);
- ~MainWindow() { delete _ui; }
- public slots:
- void run() { _core.run(); }
- void upd();
- private:
- Ui::MainWindow *_ui;
- MwObserver _observer;
- Core _core;
- };
- #endif
- //mainwindow.cpp
- #include "mainwindow.h"
- #include "ui_mainwindow.h"
- MainWindow::MainWindow(QWidget *parent) :
- QMainWindow(parent),
- _ui(new Ui::MainWindow),
- _observer(this)
- {
- _ui->setupUi(this);
- connect(_ui->pushButtonRun, SIGNAL(clicked(bool)), this, SLOT(run()));
- connect(&_observer, SIGNAL(SomeEvent()), this, SLOT(upd()));
- }
- void MainWindow::upd()
- {
- _core.lock();
- setWindowTitle(QString::number(_core.ii()));
- _core.unlock();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement