From f7ecf0953780f0442271d3b1a8c3d1d4d34ead5c Mon Sep 17 00:00:00 2001 From: Bojidar Marinov Date: Wed, 7 Oct 2015 12:06:22 +0300 Subject: [PATCH] Add lock optimisations to TCP client Close #4 --- lib/tcp/client.gd | 46 ++++++++++++++++++++++++++++++---------------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/lib/tcp/client.gd b/lib/tcp/client.gd index bd80a94..f9d72fe 100644 --- a/lib/tcp/client.gd +++ b/lib/tcp/client.gd @@ -6,10 +6,14 @@ const ReadWriteLock = preload("../ReadWriteLock.gd") var tcp_stream = StreamPeerTCP.new() var packet_peer = PacketPeerStream.new() -var client_running -var message_queue = [] var M_tcp_stream = Mutex.new() +var message_queue = [] +var M_message_queue = Mutex.new() + +var client_running +var M_client_running = Mutex.new() + var loop_thread = Thread.new() func _init(): @@ -26,35 +30,45 @@ func connect_to(host, port): M_tcp_stream.unlock() +func send(message): + M_message_queue.lock() + + message_queue.push_back(message) + + M_message_queue.unlock() + +func stop(): + M_client_running.lock() + + client_running = false + + M_client_running.unlock() + func loop(data): while true: M_tcp_stream.lock() + M_client_running.lock() if not client_running: + M_client_running.unlock() + tcp_stream.disconnect() + M_tcp_stream.unlock() break; + else: + M_client_running.unlock() while packet_peer.get_available_packet_count(): emit_signal("message", packet_peer.get_var()) + M_message_queue.lock() + for message in message_queue: packet_peer.put_var(message) message_queue.clear() + M_message_queue.unlock() + M_tcp_stream.unlock() OS.delay_msec(100) -func send(message): - M_tcp_stream.lock() - - message_queue.push_back(message) - - M_tcp_stream.unlock() - -func stop(): - M_tcp_stream.lock() - - client_running = false - - M_tcp_stream.unlock() -