Skip to content

Commit

Permalink
Add locking and event systems for data update and remove useless files
Browse files Browse the repository at this point in the history
  • Loading branch information
corentinlger committed Feb 5, 2024
1 parent b0e2e01 commit aec3855
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 100 deletions.
27 changes: 0 additions & 27 deletions client.py

This file was deleted.

63 changes: 0 additions & 63 deletions server.py

This file was deleted.

File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -19,30 +19,42 @@
def generate_random_array():
return np.random.randint(0, 10, size=(5, 5))

def broadcast(data):
pickled_data = pickle.dumps(data)
for client in clients:
client.send(pickled_data)
print(f"sent {data} to server")
def update_latest_data():
global latest_data
while True:
with data_lock:
latest_data = generate_random_array()
new_data_event.set()
time.sleep(1)

def handle_client(client):
while True:
try:
data = generate_random_array()
broadcast(data)
time.sleep(1)
new_data_event.wait()
with data_lock:
data = latest_data
client.send(pickle.dumps(data))
new_data_event.clear()

except socket.error as e:
print(f"error: {e}")
client.close()
print(f"Client {client} disconnected")
break

clients = []
# Create a global variable to store the current data + lock and event to access it
latest_data = generate_random_array()
data_lock = threading.Lock()
new_data_event = threading.Event()

# Create a thread to continuously update the data
update_data_thread = threading.Thread(target=update_latest_data)
update_data_thread.start()

# Start listening to clients and launch their threads
while True:
try:
client, addr = server.accept()
clients.append(client)
print(f"Connected with {addr}")

client_thread = threading.Thread(target=handle_client, args=(client, ))
Expand Down

0 comments on commit aec3855

Please sign in to comment.