C++ select() 函数如何在 Unix 操作系统中工作? [英] How C++ select() function works in Unix OSs?

查看:52
本文介绍了C++ select() 函数如何在 Unix 操作系统中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用select() 函数来实现服务器,但现在我必须自己实现它(作为项目的一部分).

I have used the select() function to implement servers, but now I have to implement it by myself (as a part of a project).

int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);

谁能帮我实现这个功能?任何来源,文章?任何人都可以解释该功能中发生的事情吗?

Can anyone please help me to implement this function? Any sources, articles? Can anyone explain what is happening in that function?

推荐答案

select 是一个操作系统原语.无法使用其他可移植结构(例如 pthread)来实现.

select is an operating system primitive. It cannot be implemented using other portable constructs, such as pthreads.

您可以将其视为 pthread_cond_wait 的不同专业版本,它接收与条件变量关联的信号.pthread_cond_wait 暂停当前线程,直到接收到信号,然后(可选)验证信号是否与适当的互斥锁相关联,然后获取互斥锁,并继续.select 接收信号,确认(或至少保证)它的接收,并传递信息.它还处理在调用之前接收到的信号.

You can think of it as a differently-specialized version of pthread_cond_wait, which receives a signal associated with a condition variable. pthread_cond_wait stalls the current thread until the signal is received, then (optionally) verifies that the signal was associated with the appropriate mutex, then acquires the mutex, and continues along. select receives a signal, confirms (or at least guarantees) its receipt, and passes the information along. It also deals with signals that were received before it was called.

因此,pthread_cond_wait 在实现方面并不是真正原始的;它被设计为在语义上非常安全.这就是 pthreads 的精神,无论好坏.各种库中可用的原子变量为同步作业的 pthread 提供了一种不安全的原始实现替代方案,但信号涉及调度和取消调度线程,这是非常特定于平台的.(好吧,再想一想,我猜你可以用自旋锁实现 select .我一想到这个就发抖.)

So, pthread_cond_wait is not really primitive in terms of implementation; it's designed to be very safe semantically. That is the spirit of pthreads, for better or worse. Atomic variables, available in various libraries, provide an unsafe primitive-implementation alternative to pthreads for synchronization jobs, but signaling involves scheduling and unscheduling threads, which is pretty platform specific. (Well, on second thought, I guess you could implement select with spinlocks. I shudder at the thought.)

不过,这是一个很好的练习.

It's a great exercise to try, though.

这篇关于C++ select() 函数如何在 Unix 操作系统中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆