Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running thread in background in c++11

I have a class with a connect_to method which I'm starting a thread in it, after calling it and joining it, I expected the thread to run in the background and the program execution would continue but it hangs in my connect_to method until the thread execution stops. I remember I used to work with threads in C# and they ran in the background once I started them.

#ifndef _TCP_CLIENT_H_
#define _TCP_CLIENT_H_

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

void connection_thread(void *user);


class TCPClient
{

public:
    SOCKET                m_ConnectSocket = INVALID_SOCKET;
    char                  m_recvbuf[BUFFER_LENGTH];
    int                   m_recvbuflen = BUFFER_LENGTH;
    struct addrinfo*      m_result = NULL, *m_ptr = NULL, m_hints;
    vector<PacketInfo*>   m_packet_list;
    PacketInfo*           m_packet_data = new PacketInfo();
    thread*               m_conn_thread;

    int state = 0;
    char* ip_address;
    unsigned int port = 0;

    TCPClient() {}
    ~TCPClient() {
        delete m_packet_data;
    }


    int Init_Sockets() {
        WSADATA wsaData;
        int iResult;

        iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
        if (iResult != 0) {
            printf("WSAStartup failed with error: %d\n", iResult);
            return 0;
        }
        return 1;
    }



    int Connect_to(char* ip, unsigned int port_number) {
        port = port_number;
        ip_address = ip;

        //thread conn_thread(connection_thread, this);
                thread conn_thread([=]() {connection_thread(this); return 1; });
        conn_thread.join();



        state = 0;
        return 1;
    }


}; // end TCPClient class




void connection_thread(void *user) {
    TCPClient * self = static_cast<TCPClient*>(user);


        // connecting code here... //


    self->state = CONNECTED;
    do {

        iResult = recv(self->m_ConnectSocket, self->m_recvbuf, self->m_recvbuflen, 0);
        if (iResult > 0) {
            printf("Bytes received: %d\n", iResult);
        }
        else if (iResult == 0) {
            printf("Connection closed\n");
            self->state = DISCONNECTED;
        }
        else {
            //printf("recv failed with error: %d\n", WSAGetLastError());
        }

    }
    while (iResult > 0);
}

#endif

The thread works as intended and is on a constant loop until the connection closes. Any idea what I'm missing?

like image 603
Skrakle Avatar asked Sep 15 '25 03:09

Skrakle


1 Answers

I have a class with a connect_to method which i'm starting a thread in it, after calling it and joining it, i expected the thread to run in the background and the program execution would continue but it hangs in my connect_to method until the thread execution stops

That's literally what joining a thread is supposed to do!

If you don't want to join to the thread, then simply don't. :)

Though, probably, you should at least do it in your class destructor or at some other later time, so that your main thread cannot try to end while the worker thread is still executing. Because that will end in tears...

It seems to me that this is a perfect example of why we should not write lines of code with no understanding as to why we're doing so. :) You've made an assumption about what conn_thread.join() means, an assumption that is wrong: one of the first things to do in this situation is to read the documentation to make sure your assumptions hold. Ideally you'd have read it before writing the code, but never mind.

like image 179
Lightness Races in Orbit Avatar answered Sep 16 '25 19:09

Lightness Races in Orbit