Qt 中高效的多线程服务器实现
我正在计划用 Qt 编写一个多线程服务器。每个连接都将在一个单独的线程中进行。每个线程都将运行自己的事件循环并使用异步套接字。我想以最有效的方式从主线程分派一个 const 值(例如,包含事件字符串的 QString)到所有客户端线程。当所有客户端线程都读取该值时,显然应该删除该值。
如果我只是在排队的信号/槽连接中传递数据,这会带来相当大的开销吗?传递 QSharedPointer
I'm planning a multithreaded server written in Qt. Each connection would be attended in a separate thread. Each of those threads would run its own event loop and use asynchronous sockets. I would like to dispatch a const value (for instance, a QString containing an event string) from the main thread to all the client threads in the most efficient possible way. The value should obviously be deleted when all the client threads have read it.
If I simply pass the data in a queued signal/slot connection, would this introduce a considerable overhead? Would it be more efficient to pass a QSharedPointer<QString>? What about passing a const QString* together with a QAtomicInt* for the reference counting and letting the thread decrease it and delete it when the reference counter reaches 0?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有点偏离主题,但请注意,每个连接一个线程模型可以使任何能够连接的人对运行服务器的系统进行高效的拒绝服务攻击,因为可以的最大线程数在任何系统上创建的内容都是有限的。另外,如果是 32 位,您也可能会导致地址空间不足,因为每个线程都有自己的堆栈。默认堆栈大小因系统而异。在 Win32 上,它是 1 MB,IIRC,因此保持打开和活动状态的 2048 个连接将占用 2 GB,即为用户空间保留的整个地址空间(您可以将其增加到 3 GB,但这没有多大帮助。)
有关更多详细信息,检查C10K问题,特别是I/O 策略 ->每个服务器线程为一个客户端提供服务一章。
Somewhat off-topic, but please be aware that the one-thread-per-connection model could enable anyone able to connect to conduct a highly efficient denial of service attack against the system running the server, since the maximum number of threads that can be created on any system is limited. Also, if it's 32-bit, you can also starve address space since each thread gets its own stack. The default stack size varies acorss systems. On Win32 it's 1 MB, IIRC, so 2048 connections kept open and alive will eat 2 GB, i.e. the entire address space reserved for userspace (you can bump it up to 3 GB but that doesn't help much.)
For more details, check The C10K Problem, specifically the I/O Strategies -> Serve one client with each server thread chapter.
根据文档:
基于此,与其他建议的解决方案相比,通过排队的信号/槽连接发送字符串副本的开销不应更大。因此,除非这是一个明显的性能问题,否则我不会担心它。
According to the documentation:
Based on this, you shouldn't have any more overhead sending copies of strings through the queued signal/slot connections than you would with your other proposed solutions. So I wouldn't worry about it until and unless it is a demonstrable performance problem.