Multiple threads in one class

Viewed 45

When we talk about multi-thread architecture I mean non-dependent threads for each other. The question is: Is it possible to have more threads in one class. Because in the many examples of source code, I see only codes where every thread is stored in the separated class, as we can see in the attached example.

Is it possible to create the one class with many threads and how to call these threads?

Because in the mainwindow.cpp, we can see mThrX.start(). Which call myThread_X.run(); method. So, is it possible to do a redirect to a different method and how?

I believe that my question is clear.

I've seen a similar question here, but it's a Java solution and it does not solve my problem. Multiple threads in on class

Thank for every comment and advice. ;)

Example multi-thread in separated classes:

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mThr1 = new myThread_1;
    mThr2 = new myThread_2;
    mThr3 = new myThread_3;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    mThr1->start();
    mThr2->start(QThread::HighestPriority);
    mThr3->start();

}

void MainWindow::on_pushButton_2_clicked()
{
    mThr1->stop = true;
    mThr2->stop = true;
    mThr3->stop = true;
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QThread>
#include <mythread_1.h>
#include <mythread_2.h>
#include <mythread_3.h>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

    myThread_1 *mThr1;
    myThread_2 *mThr2;
    myThread_3 *mThr3;    

private slots:
    void on_pushButton_clicked();
    void on_pushButton_2_clicked();

private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

myThread_1.cpp

#include "mythread_1.h"

myThread_1::myThread_1(){
}

void myThread_1::run(){
    QMutex mut;
    while(1){
        mut.lock();
        if(this->stop){
            this->stop = false;
            break;
        }
        mut.unlock();
        //Next part of code
        qDebug() << "Thread1";
        
    }
}

myThread_1.h

#ifndef MYTHREAD_1_H
#define MYTHREAD_1_H

#include <QThread>
#include <QDebug>
#include <QMutex>




class myThread_1 : public  QThread
{
public:
    myThread_1();
    bool stop;
    void run();

};

#endif // MYTHREAD_1_H

The myThread_2.cpp/.h and myThread_3.cpp/h are totally same as myThread_1.cpp/.h

0 Answers
Related