C++ (Qt)void Mom::fill(){ m_plate.setPlums( 100 );}
C++ (Qt)void ChildThread::run( void ){ while (doEat) { childSemaphore.acquire(); if (!childSemaphore.available()) mamaSemaphore.release(); }}
C++ (Qt)void ChildThread::run( void ){ while (doEat) { mutex.lock(); while (numPlum == 0) { condition.wait(&mutex); if (!doEat) { mutex.unlock(); return; } } --numPlum; if (!numPlum) condition.wakeAll(&mutex); mutex.unlock(); // здесь задержка, статистика }} void MamaThread::run( void ){ while (doEat) { QMutexLocker lock(&mutex); while (numPlum > 0) { condition.wat(&mutex); if (!doEat) return; } numPlum = maxPlum; // const int maxPlum = 100 condition.wakeAll(&mutex); }} void StopEat( void ){ doEat = false; QMutexLocker lock(&mutex); condition.wakeAll();}
#ifndef CANNIBALS_H#define CANNIBALS_H#include "mainwindow.h"#include <QThread>#include <thread>#include <mutex>#include <time.h>class Cannibals : public QThread{ Q_OBJECTpublic: explicit Cannibals(QObject *parent = 0); void Cooking(); void Dinner(); void Dinner_a(int);private: std::thread Cook; std::mutex eating; int food=10;signals: void NumberChanged(int);public slots:};#endif // CANNIBALS_H
#include "cannibals.h"#include "mainwindow.h"#define M 100Cannibals::Cannibals(QObject *parent) : QThread(parent){}void Cannibals::Cooking(){ food=M;}void Cannibals::Dinner_a(int z) { eating.lock(); for(int i=0; i<z;i++){ Dinner();} eating.unlock(); }void Cannibals::Dinner(){ if(food!=0){ emit NumberChanged(food); --food;} else Cook = std::thread(&Cannibals::Cooking, this); Cook.join(); msleep(rand()%2000);}
#ifndef MAINWINDOW_H#define MAINWINDOW_H#include "cannibals.h"#include <ui_mainwindow.h>#include <QMainWindow>#include <thread>#define N 20namespace Ui {class MainWindow;}class MainWindow : public QMainWindow{ Q_OBJECTpublic: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); Cannibals *Foo;private slots: void on_pushButton_clicked();private: Ui::MainWindow *ui; std::thread Cannibal[N];public slots: void OnNumberChanged (int);};#endif // MAINWINDOW_H
#include "mainwindow.h"#include "ui_mainwindow.h"#define N 20#define M 100#define P (M/N)MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); connect(Foo,SIGNAL(NumberChanged(int)),this,SLOT(OnNumberChanged(int)));}MainWindow::~MainWindow(){ delete ui;}void MainWindow::on_pushButton_clicked() { for(int i=0;i<N;i++) { Cannibal[i] = std::thread(&Cannibals::Dinner_a, Foo, P); } for(int i=0;i<N;i++) { Cannibal[i].join(); }}void MainWindow::OnNumberChanged(int Num){ ui->listWidget->clear(); ui->pushButton->setEnabled(false); ui->listWidget->addItem(QString(Num) + " cannibal ate");}