Search code examples
c++multithreadingqtc++14qwidget

Why my program is terminated but main thread is run?


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);

}

Solution

  • 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.