在辅助线程中调用 select()/pselect() 会导致主线程阻塞吗?
我正在开发一个应用程序,它需要几个辅助线程,每个辅助线程负责多个文件句柄(至少 1 个,最多 10 个)。文件句柄不在线程之间共享,因此当选择查看准备读/写的内容时,我不必担心一个辅助线程会阻塞另一个线程。我想确定的是,在执行 select
/pselect
调用时,辅助线程都不会导致主线程停止执行。
我想这不是一个问题——人们会想象这样的事情会在网络服务器中完成——但当我用谷歌搜索时,我找不到任何具体说“是的,你可以做到这一点”的东西。我的假设是否正确,即这不会造成任何问题?
为了澄清起见,我的内容看起来像:
主执行线程(
select()
循环处理传入命令消息和传出响应)辅助线程#1(
select()
循环提供服务)辅助线程#2(
select()
循环提供另一个服务)
正如我之前提到的,没有一个文件句柄在线程之间共享 - 它们是在单个线程中创建、使用和销毁的,而其他线程不知道它们的存在。
I have an application that I'm working on that requires a couple of secondary threads, and each will be responsible for a number of file handles (at least 1, upwards of 10). The file handles are not shared amongst the threads, so I don't have to worry about one secondary thread blocking the other when select
ing to see what is ready to read/write. What I want to be sure of is that neither of the secondary threads will cause the main thread to stop executing while the select
/pselect
call is executing.
I would imagine that this is not a problem - one would imagine that such things would be done in, say, a web server - but I couldn't find anything that specifically said "yes, you can do this" when I Googled. Am I correct in my assumption that this will not cause any problems?
For clarification, what I have looks something like:
Main thread of execution (
select()
loop handling incoming command messages and outgoing responses )Secondary thread #1 (
select()
loop providing a service )Secondary thread #2 (
select()
loop providing another service )
As I previously mentioned, none of the file handles are shared amongst the threads - they are created, used, and destroyed within an individual thread, with the other threads ignorant of their existence.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,你不必担心它们会阻塞主线程。我在各种项目中的多线程中使用了 select。只要它们具有不同的 FDSETS 就可以了,并且每一个都可以像独立的事件循环一样使用。
No you don't have to worry about them blocking the main thread. I have used select in multiple threads in various projects. As long as they have distinct FDSETS then you're fine and each one can be used like an independent event loop.
select 不是应该阻止整个过程吗?您是否尝试过在套接字上设置非阻塞模式?另外,请参阅 select_tut 联机帮助页以获得一些帮助。
以下是
select_tut
联机帮助页中的相关部分:那么select()
有什么意义呢?我不能随时读取和写入我的描述符吗?select()
的要点是它同时监视多个描述符,并在没有活动的情况下正确地将进程置于睡眠状态。Isn't select supposed to block the whole process?
Have you tried to set the nonblocking mode on the socket?
Also, see select_tut manpage for some help.
Here's a relevant section from the
select_tut
manpage:So what is the point of select()? Can't I just read and write to my descriptors whenever I want? The point of select() is that it watches multiple descriptors at the same time and properly puts the process to sleep if there is no activity.