問題描述
我有一個循環,它基本上每隔幾秒(超時后)調用一次:
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.
這篇關于從套接字選擇中跳出的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!