How can I join a thread executing a function from the mainWindow (Principal) class?

I received this error message while compiling my project:

"Cannot convert 'Principal :: setValues' from type 'void * (Principal: :) (void *)' to enter 'void * () (void)'" ...

enter code here 
void* Principal:: setValues(void*){
    QString velocidadCARGA=QString::number(VelocidadCargador);    
    QString velocidadLAVA=QString::number(VelocidadLavado);
    ui->Velocidad_Carga->setText(velocidadCARGA);
    ui->Velocidad_Lavado->setText(velocidadLAVA);
    ui->lbl_CantidadActual_Banda_Principal->setNum(botellasCargadas);
    return NULL;
}


void Principal::on_Start_Cargador_clicked(){
    pthread_t hilo3;
    pthread_create(&hilo3,NULL,setValues,NULL);//error in this line.
    pthread_join(hilo3,NULL);
}
+4
source share
1 answer

Principal::setValuesis a member function, so its type does not match the type of function required pthread_create.

To run a member function in a stream, you can declare some static method and pass an object into it this:

class Principal
{
...
static void* setValuesThread(void *data);
...
}

void* Principal::setValuesThread(void *data)
{
    Principal *self = reinterpret_cast<Principal*>(data);
    self->setValues();
    return NULL;
}

// your code
void Principal::setValues()
{
    QString velocidadCARGA=QString::number(VelocidadCargador);    
    QString velocidadLAVA=QString::number(VelocidadLavado);
    ui->Velocidad_Carga->setText(velocidadCARGA);
    ui->Velocidad_Lavado->setText(velocidadLAVA);
    ui->lbl_CantidadActual_Banda_Principal->setNum(botellasCargadas);
}

void Principal::on_Start_Cargador_clicked()
{
    pthread_t hilo3;
    pthread_create(&hilo3, NULL, Principal::setValuesThread, this);
    pthread_join(hilo3,NULL);
}

Principal - Qt ( , ), , Qt .

, QThread Qt /.

:

class MyThread : public QThread
{
    Q_OBJECT
public:
    MyThread(QObject *parent = 0);

    void run();

signals:
    void dataReady(QString data);
}

void MyThread::run()
{
    QString data = "Some data calculated in this worker thread";
    emit dataReady(data);
}

class Principal
{
...
public slots:
   void setData(QString data);
}

void Principal::setData(QString data)
{
    ui->someLabel->setText(data);
}

void Principal::on_Start_Cargador_clicked()
{
    MyThread *thread = new MyThread;
    connect(thread, SIGNAL(dataReady(QString)), this, SLOT(setData(QString()));
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    thread->start();
}

Qt:

http://doc.qt.io/qt-5/thread-basics.html

http://doc.qt.io/qt-5/threads-technologies.html

+3

Source: https://habr.com/ru/post/1607207/


All Articles