Qt 中高效的多线程服务器实现

发布于 2024-10-09 07:05:03 字数 303 浏览 0 评论 0原文

我正在计划用 Qt 编写一个多线程服务器。每个连接都将在一个单独的线程中进行。每个线程都将运行自己的事件循环并使用异步套接字。我想以最有效的方式从主线程分派一个 const 值(例如,包含事件字符串的 QString)到所有客户端线程。当所有客户端线程都读取该值时,显然应该删除该值。

如果我只是在排队的信号/槽连接中传递数据,这会带来相当大的开销吗?传递 QSharedPointer会更有效吗?如何将 const QString* 与 QAtomicInt* 一起传递以进行引用计数,并让线程减少它并在引用计数器达到 0 时删除它?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不及他 2024-10-16 07:05:03

有点偏离主题,但请注意,每个连接一个线程模型可以使任何能够连接的人对运行服务器的系统进行高效的拒绝服务攻击,因为可以的最大线程数在任何系统上创建的内容都是有限的。另外,如果是 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.

·深蓝 2024-10-16 07:05:03

根据文档

在幕后,QString 使用隐式共享(写入时复制)来减少内存使用并避免不必要的数据复制。

基于此,与其他建议的解决方案相比,通过排队的信号/槽连接发送字符串副本的开销不应更大。因此,除非这是一个明显的性能问题,否则我不会担心它。

According to the documentation:

Behind the scenes, QString uses implicit sharing (copy-on-write) to reduce memory usage and to avoid the needless copying of data.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文