我正在调用 FD_SET() 来设置非阻塞套接字的 write_fd,而 select() 在另一个线程中阻塞——问题是即使 fd 准备好写入,select() 也会继续阻塞。
我真正想做的是:在另一个线程中准备要为此套接字写入的数据,然后将套接字添加到 write_fd。select() 线程应该识别并处理准备好的数据。
阻塞时 select() 不能识别 fd 中的更改吗?如果是 - 是否有类似 epoll() EPOLL_CTL_MOD 而不是 FD_SET() 来更新集合;或者是识别更改以设置 select() 函数的超时的唯一方法?
在我看来,这不是一个解决方案,因为这会“慢”并且会产生 CPU 开销......
编辑:
// This thread is running all day long ...
static void * workman() {
FD_ZERO(&fd_read);
FD_ZERO(&fd_write);
FD_SET(socketId , &fd_read);
while(1) {
// PROBLEM Keeps blocking when box() is called
select(socketId+1, &fd_read, &fd_write, NULL, NULL);
if(FD_ISSET(socketId, &fd_read)) {
// RECIVE DATA
}
else if(FD_ISSET(socketId, &fd_write)) {
FD_CLR(socketId, &fd_write);
pthread_mutex_lock(&interface.mutex);
strncpy(conn.outBuffer, interface.buffer, strlen(interface.buffer));
interface.buffer[0] = '\0';
pthread_mutex_unlock(&interface.mutex);
// SEND DATA
}
}
return 0;
}
// This function is called within another thread on user input
int box(char *content) {
pthread_mutex_lock(&interface.mutex);
// preparing the data and write it into interface.buffer if available
pthread_mutex_unlock(&interface.mutex);
FD_SET(socketId, &fd_write);
return 0;
}