简体   繁体   English

基本服务器占用大量CPU资源-如何缓解?

[英]Basic server taking up massive CPU resources- how to alleviate?

I'm writing a pretty basic server in C++. 我正在用C ++写一个非常基本的服务器。

I've ended up with an architecture similar to this: 我最终得到了类似于以下的架构:

One thread (the server) is constantly looping over accept() waiting for connections (docs) . 一个线程(服务器)不断循环遍历accept()等待连接(docs)

Every connection it finds, it spawns a thread that loops over recv() waiting for something to read, and send() that sends out anything in its queue (recv docs) , (send docs) . 找到的每个连接都会产生一个线程,该线程在recv()上循环,等待读取内容,然后在send()上发送队列中的任何内容(recv docs)(send docs)

However, I want to be able to (from an external thread) tell either the server or individual connections to essentially kill themselves. 但是,我希望能够(从外部线程)告诉服务器或单个连接本质上杀死自己。 The problem is that accept() and recv() both block until they find any activity, so there's no way for them to check if their should_kill_self member is set or anything. 问题在于accept()recv()都阻塞,直到找到任何活动为止,因此它们无法检查是否应该设置其should_kill_self成员或其他任何东西。 So to fix that, I called fcntl(sock_fd, F_SETFL, O_NONBLOCK) on the file descriptors so that they won't. 因此,为了解决此问题,我在文件描述符上调用了fcntl(sock_fd, F_SETFL, O_NONBLOCK) ,以便它们不会出现。

This way, I have the server constantly looping over accept() and checking should_kill_self , and I have each connection looping over recv() , check if anything in queue to send() , and checking should_kill_self . 这样,我让服务器不断循环遍历accept()并检查should_kill_self ,并且让每个连接都循环遍历recv() ,检查队列中是否有任何要send() ,并检查should_kill_self

So this way, I can signal them to kill themselves at any time, but a side effect I've noticed is that they are taking up huge amounts of processing. 因此,通过这种方式,我可以随时通知他们杀死自己,但是我注意到的副作用是它们占用了大量的处理资源。 I am wondering if with this setup I'm doing something stupid resulting in redundant computation. 我想知道是否通过这种设置做的愚蠢的操作导致冗余计算。 I don't need this to be a super-low-latency server AT ALL, so is the "correct" way to alleviate this by like, sleeping for 10 seconds between every loop? 我根本不需要这是一个超低延迟服务器,那么通过在每个循环之间睡眠10秒钟来缓解这种情况的“正确”方法是吗?

I'm new to writing networking code, so I'm pretty sure I'm just doing something stupid. 我是编写网络代码的新手,所以我可以肯定我只是在做一些愚蠢的事情。 Any advice would be greatly appreciated! 任何建议将不胜感激!

You probably need to explore non-blocking IO in Linux or IO completion ports on windows. 您可能需要探索Linux中的非阻塞IO或Windows上的IO完成端口。 See here and here . 看到这里这里

Programming these needs extra effort and is abit harder than programming the simple socket server. 对这些进行编程需要额外的精力,并且比对简单的套接字服务器进行编程要困难得多。 However, there are libraries that will wrap non-blocking IO (and IOCP) and provides a simple interface for you to use. 但是,有些库将包装非阻塞IO(和IOCP),并为您提供了一个简单的接口。 One example being ASIO in boost. ASIO就是其中一个例子。 There are many other libraries even for Java and other languages. 还有许多其他库,甚至适用于Java和其他语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM