Python server program has high cpu usage
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Sunrise at the Stream
--
Chapters
00:00 Python Server Program Has High Cpu Usage
01:21 Accepted Answer Score 6
01:39 Answer 2 Score 4
01:56 Answer 3 Score 2
02:21 Thank you
--
Full question
https://stackoverflow.com/questions/2383...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #multithreading #tcp
#avk47
ACCEPTED ANSWER
Score 6
You are using setblocking(0), that means your socket is not blocking. What you are doing is called polling and will use as much CPU as it can.
When you use threading you don't need to poll. Just remove the setblocking(0) line and it should work properly.
ANSWER 2
Score 4
The problem is the infinite while loop (while 1). Please include a few microsecond delay (time.sleep(0.001)), this brings the CPU usage drastically down.
ANSWER 3
Score 2
To low reputation to just comment on rsy's answer. In your particular case, when you receive data with "conn.recv", just setting setblocking(1) solves the problem, as pmoleri has answered.
But if you do polling in a loop with "select" statement, just setblocking(1) has no effect and rsy's solution with a short delay (time.delay(0.01)) is the way to go.