accept() 线程安全吗? [英] Is accept() thread-safe?

查看:69
本文介绍了accept() 线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为我正在做的一门课程用 C 语言编写一个简单的网络服务器.一个要求是我们实现一个线程池来处理使用 pthreads 的连接.

I'm currently writing a simple webserver in C for a course I'm doing. One requirement is for us to implement a thread pool to handle connections using pthreads.

我知道我将如何粗略地执行此操作(在主线程中调用 accept 并将文件描述符传递给 freee 线程),但是我的朋友建议了一种替代方法,而不是我想到的方法:创建我的所有线程预先,并让他们在接受呼叫时永远循环.这个想法是,accept 将阻塞所有空闲线程,并且当一个连接进来时,只给一个文件描述符.然后,当给定线程完成连接时,它会循环返回并阻塞再次接受的调用.本质上使用对 accept() 的调用作为信号量.他认为这将大大简化实现,因为您不需要跟踪哪些线程忙以及哪些线程已准备好进行连接.理论上它也会有更低的延迟,因为线程可以立即开始执行.

I know how I would go about doing this roughly(calling accept in a main thread and passing the file descriptor to a freee thread), however my friend suggested an alternate method than the one I had in mind: creating all my threads up front, and getting them all to loop forever on a call to accept. The idea being that accept will block all the idle threads and when a connection comes in, only giving the file descriptor to one. Then when a given thread is done with a connection it loops back around and blocks on a call to accept again. Using the call to accept() as a semaphore essentially. This would simplify the implementation quite a bit he figures, as you wouldn't need to keep track of which threads are busy and which are ready for a connection. It would also be lower latency in theory, as the thread can immediately start executing.

我的问题是,这安全吗?我打算实施它并尝试一下,但我还没有准备好,我很想知道答案.我在谷歌和这里的 stackoverflow 上搜索过,但找不到任何人这样做.接受线程安全吗?我认为这种方法会带来更多开销,因为您一直在运行所有线程,这两种方法是否只是简单的内存/延迟权衡?

My question is, is this safe? I'm planning to implement it and try it out, but I'm not ready yet and I'm quite curious to know the answer. I've searched on google and here on stackoverflow, but couldn't find anyone doing it this way. Is accept thread safe? I assume there will be more overhead with this approach as you are running all your threads all the time, are the two approaches simply a simple memory/latency tradeoff?

我不确定这是否应该是社区维基,如果应该是抱歉,我找不到按钮:P

I'm unsure if this should be community wiki, apologies if it should be, I can't find the button :P

推荐答案

是的.这是设计多线程服务器的常用方法和公认的设计实践.

Yes. This is a common way to design multithreaded servers and accepted design practice.

您也可以多次fork并让子进程调用accept,这将允许您在不需要线程库的情况下进行多线程处理.较旧的服务器会这样做.

You can also fork several times and have the child processes call accept, this will allow you to do multithreading without needing a threads library. Older servers do this.

这篇关于accept() 线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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