Home > Enterprise >  Why my program is terminated but main thread is run?
Why my program is terminated but main thread is run?

Time:04-26

I run thread in Qmainwindow using thread library not qthread I not use thread.join but main thread is run but program is terminated why program is temianted?

void MainWindow::onSendMsg()
{
// std::thread trdSend([this](){
    socket = new QTcpSocket(this);
    socket->connectToHost(clientIP,clientPort.toUInt());
//socket->close();
QLabel *lblMsg = new QLabel;
QByteArray data;

qDebug()<<"New Message";

if(filePath.isNull() || filePath.isEmpty())
{
    qDebug()<<"Message is Text";

    QString msg=leMsg->text();

    qDebug()<<"Message : "<< msg;

    data =msg.toUtf8();
    data.insert(0,'0');
    qDebug()<<"Add Flag To Message";
    //lblMsg->setText(msg);

    qDebug()<<"Message Is Ready";
    socket->write(data);
    std::thread trdSend((Send()),&data);
    //trdSend.join();
    emit addWidget(true,true,data);

}

CodePudding user response:

The std::thread trdSend leaves scope so its destructor is called without thread being joined. So it is still joinable. Therefore the program is required to terminate.

It terminates because what your code does is programming error. It is made that way because we want either:

  1. work thread to send our main program some kind of signal about if it succeeded or failed and so our program knows that the work is done and thread can be joined.
  2. our main thread to wait in join until work is done.
  3. detach the thread as we don't really care how it went. But that is odd so we have to be explicit there.

CodePudding user response:

Literally from std::thread::~thread:

~thread(); (since C 11)

Destroys the thread object.

If *this has an associated thread (joinable() == true), std::terminate() is called.

Notes

A thread object does not have an associated thread (and is safe to destroy) after

  • it was default-constructed
  • it was moved from
  • join() has been called
  • detach() has been called

The instance std::thread trdSend; is created as local variable. After the emit addWidget(true,true,data); the scope is left and the trdSend is destroyed while none of the four conditions is met.

  • Related