gpt4 book ai didi

c++ - c++11后台运行线程

转载 作者:太空狗 更新时间:2023-10-29 19:57:45 25 4
gpt4 key购买 nike

我有一个带有 connect_to 方法的类,我在其中启动了一个线程,在调用它并加入它之后,我希望该线程在后台运行并且程序会继续执行,但它卡在我的 connect_to 方法,直到线程执行停止。我记得我曾经在 C# 中使用线程,一旦我启动它们,它们就会在后台运行。

#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

线程按预期工作,并一直循环直到连接关闭。知道我错过了什么吗?

最佳答案

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

从字面上看,这就是加入线程应该做的!

如果您不想加入线程,那就干脆不要。 :)

不过,也许您至少应该在您的类析构函数中或稍后的某个时间执行此操作,这样您的主线程就不会在工作线程仍在执行时尝试结束。因为那将以泪水告终......

在我看来,这是一个完美的例子,说明为什么我们不应该在不理解原因的情况下编写代码行。 :) 您对 conn_thread.join() 的含义做出了一个假设,这个假设是错误的:在这种情况下首先要做的事情之一是阅读文档 以确保您的假设成立。理想情况下,您应该在编写代码之前阅读它,但没关系。

关于c++ - c++11后台运行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30195015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com