我有一个无限循环的线程,它接收和处理来自套接字的数据。我希望该线程阻塞(睡眠),直到数据在套接字上可供读取或“退出”布尔变量变为真(由不同的线程设置)。是否可以在不轮询和使用任何第三方库(当然套接字库除外)的情况下以可移植的方式做到这一点?如果不可能以可移植的方式进行,那么在 Windows 下最好的方法是什么(仍然没有轮询和第三方库)?
示例代码:
bool exit = false; // or "std::atomic<bool> exit" or anything else
void fn()
{
SOCKET s;
// init socket, establish connection, etc
for(;;)
{
// This thread goes to wait (blocks) until data becomes available on socket
// OR exit var is set to true (by a different thread) - how?
if(exit) break;
// receive and process data from socket
}
}