Потоки и философы
Здравствуйте, реализовал обедающих философов с помощью семафоров. Но возник вопрос, как это сделать использую QMutex или QSemaphore, а не как я с помощью условий. Очень буду благодарен за помощь.
Ps. И еще такой вопрос, как в моем коде остановить потоки по кнопке стоп, а затем, если нажать старт, симуляция обеда начиналась заново? (Я так понимаю, нужно выставлять флаг цикла while в слоте life() в false, а затем вызывать для потока terminate()? )
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QThread> #include <QStringList> #include <QTableView> #include <QStandardItemModel> #include <QVector> #include "philosopher.h" #include "fork.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); public slots: void slotStart(); //начало эмуляции void slotStop(); //завершение эмуляции void slotTextOutput(QString sOut); //вывод текста в textedit private: Ui::MainWindow *ui; QThread thread1; QThread thread2; QThread thread3; QThread thread4; QThread thread5; QVector <Fork> list_fork; int listing = 1; }; #endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); connect(ui->action, SIGNAL(triggered(bool)), this, SLOT(slotStart())); connect(ui->action_2, SIGNAL(triggered(bool)), this, SLOT(slotStop())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::slotStart() { for (int i = 0; i < 5; i++) { Fork fork; list_fork.push_back(fork); } Philosopher *phil1 = new Philosopher("Socrat", &list_fork, 0); Philosopher *phil2 = new Philosopher("Arestotel", &list_fork, 1); Philosopher *phil3 = new Philosopher("Platon", &list_fork, 2); Philosopher *phil4 = new Philosopher("Evklid", &list_fork, 3); Philosopher *phil5 = new Philosopher("Diogen", &list_fork, 4); connect(phil1, SIGNAL(signalAddText(QString)), this, SLOT(slotTextOutput(QString))); connect(phil2, SIGNAL(signalAddText(QString)), this, SLOT(slotTextOutput(QString))); connect(phil3, SIGNAL(signalAddText(QString)), this, SLOT(slotTextOutput(QString))); connect(phil4, SIGNAL(signalAddText(QString)), this, SLOT(slotTextOutput(QString))); connect(phil5, SIGNAL(signalAddText(QString)), this, SLOT(slotTextOutput(QString))); connect(&thread1, SIGNAL(started()), phil1, SLOT(life())); connect(&thread2, SIGNAL(started()), phil2, SLOT(life())); connect(&thread3, SIGNAL(started()), phil3, SLOT(life())); connect(&thread4, SIGNAL(started()), phil4, SLOT(life())); connect(&thread5, SIGNAL(started()), phil5, SLOT(life())); phil1->moveToThread(&thread1); phil2->moveToThread(&thread2); phil3->moveToThread(&thread3); phil4->moveToThread(&thread4); phil5->moveToThread(&thread5); thread1.start(QThread::NormalPriority); thread2.start(QThread::NormalPriority); thread3.start(QThread::NormalPriority); thread4.start(QThread::NormalPriority); thread5.start(QThread::NormalPriority); } void MainWindow::slotStop() { } void MainWindow::slotTextOutput(QString sOut) { QString sss = QString::number(listing); sss+= ": " + sOut; ui->plainTextEdit->appendPlainText(sss); listing++; }fork.h
#ifndef FORK_H #define FORK_H class Fork { public: Fork(); bool getIsUsing() const; void take(); void put(); private: bool isUsing; }; #endif // FORK_Hfork.cpp
#include "fork.h" Fork::Fork() { isUsing = false; } bool Fork::getIsUsing() const { return isUsing; } void Fork::take() { isUsing = true; } void Fork::put() { isUsing = false; }philosopher.h
#ifndef PHILOSOPHER_H #define PHILOSOPHER_H #include <QObject> #include <windows.h> #include <QVector> #include "fork.h" class Philosopher : public QObject { Q_OBJECT public: Philosopher(QString s, QVector<Fork> *fork, int id); void eat(); void think(); void takeForks(); void putForks(); signals: void signalAddText(QString); public slots: void life(); private: QString name; bool left_fork; bool right_fork; QVector <Fork> *forkNumber; int idPhil; }; #endif // PHILOSOPHER_Hphilosopher.cpp
#include "philosopher.h" Philosopher::Philosopher(QString s, QVector<Fork> *fork, int id) : name(s) { left_fork = false; right_fork = false; forkNumber = fork; idPhil = id; } void Philosopher::eat() { QString temp = name + " кушает."; Sleep(1000); emit(signalAddText(temp)); } void Philosopher::think() { QString temp = name + " думает."; Sleep(1000); emit(signalAddText(temp)); } void Philosopher::takeForks() { if((!(*forkNumber)[idPhil].getIsUsing())&&(!(*forkNumber)[(idPhil+4)%5].getIsUsing())) { (*forkNumber)[idPhil].take(); left_fork = true; (*forkNumber)[(idPhil+4)%5].take(); right_fork = true; QString temp = name + " взял вилки."; emit(signalAddText(temp)); Sleep(1000); } } void Philosopher::putForks() { QString temp = name + " положил вилки."; emit(signalAddText(temp)); (*forkNumber)[idPhil].put(); left_fork = false; (*forkNumber)[(idPhil+4)%5].put(); right_fork = false; Sleep(1000); } void Philosopher::life() { while(true) { think(); takeForks(); if (left_fork && right_fork) { eat(); putForks(); } } }
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.Do you like it? Share on social networks!
AD
- Akiv Doros
- Nov. 11, 2024, 10:58 p.m.
C ++ - Test 004. Pointers, Arrays and Loops
- Result:50points,
- Rating points-4
m
- molni99
- Oct. 26, 2024, 8:37 a.m.
C ++ - Test 004. Pointers, Arrays and Loops
- Result:80points,
- Rating points4
m
- molni99
- Oct. 26, 2024, 8:29 a.m.
C ++ - Test 004. Pointers, Arrays and Loops
- Result:20points,
- Rating points-10
Last comments
How to make game using Qt - Lesson 3. Interaction with other objects what is priligy tablets What happens during the LASIK surgery process
Using variables declared in CMakeLists.txt inside C ++ files where can i buy priligy online safely Tom Platz How about things like we read about in the magazines like roid rage and does that really
Django - Tutorial 055. How to write auto populate field functionality Freckles because of several brand names retin a, atralin buy generic priligy
QML - Tutorial 035. Using enumerations in QML without C ++ priligy cvs 24 Together with antibiotics such as amphotericin B 10, griseofulvin 11 and streptomycin 12, chloramphenicol 9 is in the World Health Organisation s List of Essential Medici…
Qt/C++ - Lesson 052. Customization Qt Audio player in the style of AIMP It decreases stress, supports hormone balance, and regulates and increases blood flow to the reproductive organs buy priligy online safe Promising data were reported in a PDX model re…
Now discuss on the forum
добавить qlineseries в функции Listen intently to what Jerry says about Conditional Acceptance because that s the bargaining chip in the song and dance you will have to engage in to protect yourself and your family from AMI S…
Всё ещё разбираюсь с кешем. priligy walgreens levitra dulcolax carbs The third ring was found to be made up of ultra relativistic electrons, which are also present in both the outer and inner rings
IscanderCheOct. 31, 2024, 10:43 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…
ИМ
Реализация навигации по разделам Спасибо Евгений!
Игорь МаксимовOct. 3, 2024, 11:05 a.m.
Извиняюсь за поздний ответ. У вас вопрос достаточно обширный, как бы "академические" задачки требуют значительно больше времени на размышление, которого лично у меня немного.
Посмотрите вот эту статью по moveToThread , там сделан подобный функционал.