Thread.joinable return true 即使线程还没有完成执行

Thread.joinable return true even thread hasn't finished executing

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

    //........
}

问题是尽管线程中的循环仍然 运行,但线程 returns 可连接(真)。

所以这意味着控制台输出 "Connecting to server......" => "Start" => "Start2" => "Joinable returned true" 但是 "Done" 应该在 [=21 之后打印=] 除非我误解了 joinable 函数

我对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的思路就不一样了。线程始终是可连接的,除非已经 default-constructed 并且尚未分配给 function/method 到 运行 或者如果您已经在其上调用了 thread.join() 方法。

手头问题的一个相当简单的解决方案是使用一些 multithreading-aware 锁定结构,例如 std::atomic or void futures to communicate the result as suggested in the Effective Modern C++ book of Scott Meyers