The reason it's using 100% CPU is that when you have nothing to write, you just keep spinning as fast as you can until there is something to write:
while True:
SendNow
for line in SendData:
self.request.sendall(line)
SendData = []
SendNow = False
To make it not use 100% CPU, you have to find something for it to wait on.
Your fix does this by waiting on received data, but since you don't normally have any data to receive, this isn't very useful. (As you put it, "it only outputs data if I send a keystroke".)
Meanwhile:
Is there any way to pause the thread until data is sent?
Sure. And you're already doing it. That's what sendall
does. But that doesn't help. The problem is that once you've sent all of the data, you go back through the loop over and over until there's more data to send.
or can I simulate a received message to trigger a data burst from the main program?
Of course, but what would you use to trigger that simulated receive? If you're just going to spin simulating receives as fast as possible, that won't help anything.
I think what you want here is a condition variable around the data. Something like this:
SendCondition = threading.Condition()
class ThreadedServerRequestHandler(SocketServer.StreamRequestHandler):
def handle(self):
global SendCondition
global SendData
while True:
with SendCondition:
while not SendData:
SendCondition.wait()
for line in SendData:
self.request.sendall(line)
SendData = []
Then, whatever your code is that sets SendData
(which you didn't show) looks something like this:
global SendCondition
global SendData
# ...
new_send_data = <whatever>
with SendCondition:
SendData.append(new_send_data)
SendCondition.notify()