Advertisement
fafa78

Untitled

Apr 26th, 2016
485
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //mainwindow.h
  2. #ifndef MAINWINDOW_H
  3. #define MAINWINDOW_H
  4.  
  5. #include <thread>
  6. #include <mutex>
  7. #include <QMainWindow>
  8.  
  9. namespace Ui { class MainWindow; }
  10.  
  11. struct Observer
  12. {
  13.     virtual void notify() = 0;
  14. };
  15.  
  16. class Core
  17. {
  18. public:
  19.     void *run()
  20.         {
  21.             std::thread thread(&Core::runP, this);
  22.             thread.detach();
  23.         }
  24.  
  25.     void setObserver(Observer *observer) { _observer = observer; }
  26.     int ii() const { return _ii; }
  27.     void nextIi() { _ii++; }
  28.  
  29.     void lock()    { _mutex.lock(); }
  30.     bool tryLock() { return _mutex.try_lock(); }
  31.     void unlock()  { _mutex.unlock(); }
  32.  
  33. private:
  34.     void runP()
  35.         {
  36.             for (int i = 1; i <= 1000; i++) {
  37.                 if (i % 10 == 0) {
  38.                     lock();
  39.                     nextIi();
  40.                     unlock();
  41.                     notify();
  42.                 }
  43.             }
  44.         }
  45.  
  46.     void notify() { _observer->notify(); }
  47.     Observer *_observer;
  48.     int _ii;
  49.     std::mutex _mutex;
  50. };
  51.  
  52. struct MwObserver : public QObject, public Observer
  53. {
  54.     Q_OBJECT
  55.  
  56. public:
  57.     explicit MwObserver(struct MainWindow *mainWindow) { _mainWindow = mainWindow; }
  58.     virtual void notify() { emit SomeEvent(); }
  59.  
  60. signals:
  61.     void SomeEvent();
  62.  
  63. public:
  64.     MainWindow *_mainWindow;
  65. };
  66.  
  67.  
  68. class MainWindow : public QMainWindow
  69. {
  70.     Q_OBJECT
  71. public:
  72.     explicit MainWindow(QWidget *parent = 0);
  73.     ~MainWindow() { delete _ui; }
  74.  
  75. public slots:
  76.     void run() { _core.run(); }
  77.     void upd();
  78.  
  79. private:
  80.     Ui::MainWindow *_ui;
  81.     MwObserver _observer;
  82.     Core _core;
  83. };
  84.  
  85. #endif
  86.  
  87.  
  88. //mainwindow.cpp
  89. #include "mainwindow.h"
  90. #include "ui_mainwindow.h"
  91.  
  92. MainWindow::MainWindow(QWidget *parent) :
  93.     QMainWindow(parent),
  94.     _ui(new Ui::MainWindow),
  95.     _observer(this)
  96. {
  97.     _ui->setupUi(this);
  98.     connect(_ui->pushButtonRun, SIGNAL(clicked(bool)), this, SLOT(run()));
  99.     connect(&_observer, SIGNAL(SomeEvent()), this, SLOT(upd()));
  100. }
  101.  
  102. void MainWindow::upd()
  103. {
  104.     _core.lock();
  105.     setWindowTitle(QString::number(_core.ii()));
  106.     _core.unlock();
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement