- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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::atomic或 void futures按照 Effective Modern C++ book of Scott Meyers 中的建议传达结果
关于c++ - Thread.joinable 返回 true 即使线程还没有完成执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49244599/
我是一名优秀的程序员,十分优秀!