Threading in QT in c++



  • Hi All,

    i have created two thread.
    every thread has its own local variable mx_Server,mxx_Account.

    void Command_clicked()
    {
        for(int i=0;i<ip.size();i++){
           
            std::thread threadCmdExecutor(sendThread, ipList[i]);
            threadCmdExecutor.detach();
    
        }
    
    }
    
    
    sendThread(std::string val){ 
         std::stringstream ss(val);
         std::string item;
        std::vector<std::string> token;
         while(getline(ss,item,';')){
             token.push_back(item);
         }
         std::string ipAddrs=token[0];
         std::string dNames=token[1];
        ServerAccount  *mxx_Account = new ServerAccount(ipAddrs,dNames);
        Server *mx_Server = new Server(mxx_Account);
       bool status= mx_Server->connection();
       if(status){
           qDebug()<<"-connected------------";
            
        }
       else{
    
        }
       delete mx_Server;
       delete mxx_Account;
        return 0;
    }
    

    when i am not deleteting these variable it is working fine.

    when using

    delete mx_Server;
    delete mxx_Account;
    

    then one thread works fine and other crashes.

    reason is while other thread start using these variable then previous thred delete it.

    infact every thread has its own local variable then why crashes.

    please suggest me.

    Thanks me.

    [Added code tags ~kshegunov]



  • @shashi-prasad ,

    connect(mx_Server, SIGNAL(finished()), mx_Server, SLOT(deleteLater()), Qt::DirectConnection);
    connect(mxx_Account, SIGNAL(finished()), mxx_Account, SLOT(deleteLater()), Qt::DirectConnection);


  • Moderators

    @shashi-prasad Can you show the stack trace when it is crashing?
    Also what do the destructors of ServerAccount and Server do?



  • It looks like there's been a formatting error, ie std::vectorstd::string token;
    And other than a single use of qDebug(), Qt related functionality isn't invoked. It's easier to help with more complete information.

    At a glance, there's an assumption that ipAddrs is the first line of the string passed to sendThread(), and dNames is the second. There's no validation that either is in the right position, or that a first and second line even exist. Destructors relying on valid values could be the culprit.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.