HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Gossip algorithm in distributed systems

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
gossipalgorithmsystemsdistributed

Problem

I have implemented the gossip algorithm in distributed systems for review.

Gossip class

```
import random
import socket
from threading import Thread
import time

class GossipNode:
# hold infected nodes
infected_nodes = []

# initialization method.
# pass the port of the node and the ports of the nodes connected to it
def __init__(self, port, connected_nodes):
# create a new socket instance
# use SOCK_DGRAM to be able to send data without a connection
# being established (connectionless protocol)
self.node = socket.socket(type=socket.SOCK_DGRAM)

# set the address, i.e(hostname and port) of the socket
self.hostname = socket.gethostname()
self.port = port

# bind the address to the socket created
self.node.bind((self.hostname, self.port))

# set the ports of the nodes connected to it as susceptible nodes
self.susceptible_nodes = connected_nodes

print("Node started on port {0}".format(self.port))
print("Susceptible nodes =>", self.susceptible_nodes)

# call the threads to begin the magic
self.start_threads()

def input_message(self):
while True:
# input message to send to all nodes
message_to_send = input("Enter a message to send:\n")

# call send message method and pass the input message.
# encode the message into ascii
self.transmit_message(message_to_send.encode('ascii'))

def receive_message(self):
while True:
# since we are using connectionless protocol,
# we will use 'recvfrom' to receive UDP message
message_to_forward, address = self.node.recvfrom(1024)

# remove the port(node), from which the message came from,
# from the list of susceptible nodes and
# add it to the list of infected nodes
self.susceptible_nodes.remove(address[1])
GossipNode.in

Solution

First off, you should be using docstrings to describe your functions and classes, not regular comments. A typical docstring might look something like this:

def my_func( ... ):
    """
    Describe my_func and it's arguments
    in detail here.
    """
    ...


Secondly, you have a few useless comments, like # sleep for 2 seconds in order to show difference in time, or # call the threads to begin the magic. Comments like these are fairly useless and can be removed.

Other than that, this code is really nice looking!

Code Snippets

def my_func( ... ):
    """
    Describe my_func and it's arguments
    in detail here.
    """
    ...

Context

StackExchange Code Review Q#95671, answer score: 3

Revisions (0)

No revisions yet.