我可以同时从多个线程为一个套接字调用accept()吗? [英] Can I call accept() for one socket from several threads simultaneously?

查看:424
本文介绍了我可以同时从多个线程为一个套接字调用accept()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Linux 3.2.0,x86_64. 我可以同时从多个线程为一个套接字调用accept()吗?

I am using Linux 3.2.0, x86_64. Can I call accept() for one socket from several threads simultaneously?

推荐答案

是的,您可以从多个线程和多个进程的同一个侦听套接字上调用accept(),尽管指向的重点可能不如您想的那样.内核将只允许一个成功.当使用进程完成此操作时,这称为预派生,并且为每个新连接节省了fork()的开销.但是,当您处理线程时,可以更轻松地拥有一个等待新连接队列的现有线程池.一个线程执行accept并写入队列,而工作线程读取队列并执行其操作.它更干净,这是一个很好理解的模式,您几乎一无所获.

Yes, you can call accept() on the same listening socket from multiple threads and multiple process though there might not be as much point to it as you think. The kernel will only allow one to succeed. When this is done with processes it is known as pre-forking and it saves the expense of a fork() for every new connection. But when you are dealing with threads you can more easily have an existing thread pool that waits on a queue of new connections. One thread does the accept and writes the queue and the worker threads read the queue and do their thing. It's cleaner, it's a well understood pattern, and you lose almost nothing.

这篇关于我可以同时从多个线程为一个套接字调用accept()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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