gpt4 book ai didi

c++ - Thread.joinable 返回 true 即使线程还没有完成执行

转载 作者:行者123 更新时间:2023-11-28 01:35:55 25 4
gpt4 key购买 nike

std::mutex MTX;
bool ExitThread = false;

//This function is running in a separate thread
//for constantly trying to connect to a server in a non blocking manner
void ClientConnectingLoop(sf::TcpSocket* client, std::string ipAddress,
unsigned short port)
{
std::cout << "Start" << std::endl;
MTX.lock();
std::cout << "Start2" << std::endl;
while(client->connect(ipAddress, port) != sf::Socket::Status::Done &&
!ExitThread)
{

}

std::cout << "Done" << std::endl;
MTX.unlock();
}


int main()
{
//Code for setting ipaddress and port is abstracted.
std::string ipAddress;
unsigned short port;

//Setup socket
sf::TcpSocket clientSocket;
clientSocket.setBlocking(false);

//Connect to server
std::thread ClientConnectThread(ClientConnectingLoop, &clientSocket, ipAddress, port);
std::cout << "Connecting to server......" << std::endl;


//Wait until it finishes executing, code inside this loop is abstracted
while(!ClientConnectThread.joinable())
{
}

//The thread is finished executing.
if(ClientConnectThread.joinable())
{
std::cout << "Joinable returned true" << std::endl;
ClientConnectThread.join();
}

//........
}

问题是尽管线程中的循环仍在运行,但线程返回 joinable(true)。

这意味着控制台输出“连接到服务器......”=>“开始”=>“Start2”=>“Joinable returned true”但是“Done”应该在“Start2”之后打印,除非我被误解的可连接函数

我对 C++ 和 SFML 还是很陌生,请指出任何错误。

最佳答案

直接引用自cppreference.com

std::thread::joinable

Checks if the thread object identifies an active thread of execution. Specifically, returns true if get_id() != std::thread::id(). So a default constructed thread is not joinable.A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.

基于此,joinable thread的思路就不一样了。线程始终是可连接的,除非它是默认构造的并且尚未分配给要运行的函数/方法,或者您已经调用了 thread.join() 方法。

手头问题的一个相当简单的解决方案是使用一些多线程感知锁定结构,例如 std::atomicvoid futures按照 Effective Modern C++ book of Scott Meyers 中的建议传达结果

关于c++ - Thread.joinable 返回 true 即使线程还没有完成执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49244599/

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