A better way instead of using a third thread is to use threading.Lock()
to protect the socket resource because this removes the need of a third thread. You have lower overhead and less latency than if you had a third thread.
import threading
lock = threading.Lock()
def sendfunction(sock, data):
with lock:
sock.send(data)
You can call that from either of your threads but only one thread at a time will be allowed to call sock.send
. When a thread reaches the lock that is already locked by another thread it will sleep until the other thread releases the lock then it will acquire the lock and the process repeats.
The threading module contains Lock
, RLock
, and Condition
which are all very useful when dealing with multiple threads and you will find it well worth your time to become familiar with them and their usage.
You could incorporate the heartbeat into your message handling by checking the current time with the last time you sent a heartbeat before you process each message, and that would prevent being flooded with messages causing a heartbeat not to be sent. The problem is if your message handling code does not run then no heartbeats will be sent. You could alleviate this by having your message handling code get a dummy message on interval to allow it to check if it needs to send a heartbeat and just ignore the dummy message.
You should try to use threads sparingly (aim for a single thread) however in your case a thread would likely be okay since it is going to spend most of it's time sleeping. You should however not use a daemon thread because they do not properly shutdown. Although the damage might be nonexistent in your case if it did not properly shutdown it still might throw some type of fault (error message) which looks bad.
I do not agree with the multiple sockets method as I think it would actually complicate the situation. You will find a many types of network services/applications out there that incorporate the heartbeat and messages into a single socket byte stream.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…