从套接字选择中跳出

2023-01-19C/C++开发问题
2

本文介绍了从套接字选择中跳出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个循环,它基本上每隔几秒(超时后)调用一次:

I have a loop which basically calls this every few seconds (after the timeout):

 while(true){

    if(finished)
       return;

    switch(select(FD_SETSIZE, &readfds, 0, 0, &tv)){
        case SOCKET_ERROR : report bad stuff etc; return;
        default : break;
    }

    // do stuff with the incoming connection
 }

所以基本上每隔几秒钟(由电视指定),它就会重新激活聆听.

So basically for every few seconds (which is specified by tv), it reactivates the listening.

这是在线程 B(不是主线程)上运行的.有时我想从线程 A(主线程)立即结束这个接受器循环,但似乎我必须等到时间间隔结束..

This is run on thread B (not a main thread). There are times when I want to end this acceptor loop immediately from thread A (main thread), but seems like I have to wait until the time interval finishes..

有没有办法从另一个线程中断 select 函数,以便线程 B 可以立即退出?

Is there a way to disrupt the select function from another thread so thread B can quit instantly?

推荐答案

最简单的方法大概是使用 pipe(2) 创建一个管道并将读取端添加到 readfds.当另一个线程想要中断 select() 时,只需向它写入一个字节,然后再消费它.

The easiest way is probably to use pipe(2) to create a pipe and add the read end to readfds. When the other thread wants to interrupt the select() just write a byte to it, then consume it afterward.

这篇关于从套接字选择中跳出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6