×

Berkley’s Algorithm

Berkley’s Algorithm is mainly used in clock synchronization system. It is used in distributed systems. To implement this algorithm, we have to think that the network has no accurate time source and UTC server.

Algorithm

Step 1: First, it is necessary to choose one master node from the pool of nodes in the network. It will be chosen by leader election process algorithm. The elected node will be master and all other nodes will act as slave.

Step 2: The node which is considered as master node will send request for clock time to other nodes which are considered as slave nodes.

Step 3: The slave nodes will send the clock time to the master node.

Step 4: After fetching the clock time of all nodes, master node will calculate the average difference between the times received from slave nodes and its own time. After that, it will add this average to its current time and send over the network.

Note:

What is distributed system?

In a distributed system, we can’t find a physical connection between components but there is always a network to connect them. In this type of system, it is obvious that there will be individual local time for every nodes or components. But, we need a global time. So, we have to use clock synchronisation. This is the main concept behind the use of Berkley’s algorithm.

The following code is used to implement the approach to trigger master node:

Code:

# Python3 program to trigger master
from functools import reduce
from dateutil import parser
import threading
import datetime
import socket
import time
client_data = {}
def startReceivingClockTime(connector, address):


	while True:
		clock_time_string = connector.recv(1024).decode()
		clock_time = parser.parse(clock_time_string)
		clock_time_diff = datetime.datetime.now() - \
												clock_time


		client_data[address] = {
					"clock_time"	 : clock_time,
					"time_difference" : clock_time_diff,
					"connector"	 : connector
					}


		print("Client Data updated with: "+ str(address),
											end = "\n\n")
		time.sleep(5)


def startConnecting(master_server):
	
	while True:
		master_slave_connector, addr = master_server.accept()
		slave_address = str(addr[0]) + ":" + str(addr[1])


		print(slave_address + " got connected successfully")


		current_thread = threading.Thread(
						target = startReceivingClockTime,
						args = (master_slave_connector,
										slave_address, ))
		current_thread.start()


def getAverageClockDiff():


	current_client_data = client_data.copy()


	time_difference_list = list(client['time_difference']
								for client_addr, client
									in client_data.items())
									


	sum_of_clock_difference = sum(time_difference_list, \
								datetime.timedelta(0, 0))


	average_clock_difference = sum_of_clock_difference \
										/ len(client_data)


	return average_clock_difference


def synchronizeAllClocks():


	while True:


		print("New synchronization cycle started.")
		print("Number of clients to be synchronized: " + \
									str(len(client_data)))


		if len(client_data) > 0:


			average_clock_difference = getAverageClockDiff()


			for client_addr, client in client_data.items():
				try:
					synchronized_time = \
						datetime.datetime.now() + \
									average_clock_difference


					client['connector'].send(str(
							synchronized_time).encode())


				except Exception as e:
					print("Something went wrong while " + \
						"sending synchronized time " + \
						"through " + str(client_addr))


		else :
			print("No client data." + \
						" Synchronization not applicable.")


		print("\n\n")


		time.sleep(5)
def initiateClockServer(port = 8080):


	master_server = socket.socket()
	master_server.setsockopt(socket.SOL_SOCKET,
								socket.SO_REUSEADDR, 1)


	print("Socket at master node created successfully\n")
	
	master_server.bind(('', port))
	master_server.listen(10)
	print("Clock server started...\n")
	print("Starting to make connections...\n")
	master_thread = threading.Thread(
						target = startConnecting,
						args = (master_server, ))
	master_thread.start()
	print("Starting synchronization parallelly...\n")
	sync_thread = threading.Thread(
						target = synchronizeAllClocks,
						args = ())
	sync_thread.start()


if __name__ == '__main__':
	initiateClockServer(port = 8080)

Output:

New synchronization cycle started.
Number of clients to be synchronized: 3
Client Data updated with: 127.0.0.1:57284
Client Data updated with: 127.0.0.1:57274
Client Data updated with: 127.0.0.1:57272

The following code is used to trigger slave nodes:

# Python3 program to trigger slave
from timeit import default_timer as timer
from dateutil import parser
import threading
import datetime
import socket
import time
def startSendingTime(slave_client):


	while True:
		slave_client.send(str(
					datetime.datetime.now()).encode())


		print("Recent time sent successfully",
										end = "\n\n")
		time.sleep(5)
def startReceivingTime(slave_client):


	while True:
		Synchronized_time = parser.parse(
						slave_client.recv(1024).decode())


		print("Synchronized time at the client is: " + \
									str(Synchronized_time),
									end = "\n\n")
def initiateSlaveClient(port = 8080):


	slave_client = socket.socket()		
	
	slave_client.connect(('127.0.0.1', port))
	print("Starting to receive time from server\n")
	send_time_thread = threading.Thread(
					target = startSendingTime,
					args = (slave_client, ))
	send_time_thread.start()


	print("Starting to receiving " + \
						"synchronized time from server\n")
	receive_time_thread = threading.Thread(
					target = startReceivingTime,
					args = (slave_client, ))
	receive_time_thread.start()


if __name__ == '__main__':
	initiateSlaveClient(port = 8080)

Output:

Recent time sent successfully
Synchronized time at the client is: 2018-11-23 18:49:31.166449

Note:

This algorithm was invented by Gussela and Jatti at the University Of California Of Berkley so; it is named as Berkley’s algorithm. It is preferred to use this algorithm in intranet like Christian’s algorithm.


Related Topics

Delete N nodes after M nodes of a linked list

Delete N nodes after M nodes of a linked list In this problem, we have given a linked list and two integers M and N. We need to traverse the linked...

3 minutes read.

Given a Binary Tree, Check if it's balanced

Implementation /*Creating a C++ program that will help us identify whether the given tree is height-balanced or not.  */ #include <bits/stdc++.h> using namespace std; /* A particular binary tree node consists of data with some...

4 minutes read.

Minimum Spanning Tree

Before getting to know about the minimum spanning tree, we should first discuss about what is a spanning tree. A spanning tree is basically a sub or minimized graph that...

7 minutes read.

Find out the area between two concentric circles

You have given two values of the radius of two circles. You have to find out the area between these two circles. Let's take an example - For the above diagram,...

3 minutes read.

Sparse Matrix in Data Structure

Sparse Matrix The sparse matrix is a two-dimensional data object which is made by m rows and n columns, so we can say the number of data values in sparse matrix...

6 minutes read.

LCA of binary tree

Implementation //Writing a program to find the lowest common factor in a given binary search tree. #include <iostream> #include <vector> using namespace std; // the very first step is to create a binary tree. struct __nod { int...

8 minutes read.

Threaded Binary Tree

The linked form of binary trees wastes storage capacity because more than half of the connection variables have a Missing value. A binary tree has several nodes. Hence n+1 link fields...

8 minutes read.

Singly Linked list

Singly Linked list A singly linked list is a kind of linked list which is unidirectional. If we talk about singly linked list, then we can say it can be traversed...

3 minutes read.

Bookshop management system using file handling in C++

We see different software in every hospitals or library to manage their database. It is very important to store organization’s data. So we use this software. Now we are going...

5 minutes read.

Operations of B++ tree

Insertion When we discuss the insertion operation in the B++ tree, this operation helps us in pushing a new element in the tree at any given place. In this case, the...

17 minutes read.

Primitive Data Structure in C

The data structure is a logical or mathematical model for organizing and structuring the main memory or elements. We can classify the data structures in two ways one is primitive, and...

10 minutes read.

Boruvkas algorithm

This algorithm is used for finding minimum spanning tree from a weighted graph. Like prim’s and kruskal’s algorithm it is also a greedy algorithm. Note:What is the minimum spanning tree?We know...

4 minutes read.

Asymptotic Notation

Asymptotic notation is expressions that are used to represent the complexity of algorithms. The complexity of the algorithm is analyzed from two perspectives:  Time complexitySpace complexity Time complexity The time complexity of an algorithm is the...

3 minutes read.

Deletion in Binary Search Tree

Implementation #include <iostream> using namespace std; struct _nod {   int ky;   struct _nod *Lft, *Rt; }; // Creating a node in the binary tree. struct _nod *nw_nod(int Itm) {   struct _nod *temp = (struct _nod *)malloc(sizeof(struct...

4 minutes read.

Find the nth node from the end of a Linked List

Find the nth node from the end of a Linked List In this problem, we have given a singly linked list and a number 'n,' and we need to find the...

3 minutes read.

Flattening a Linked List

In this article, we are going to study about the logic behind the flattening of linked list and we also going to build a code in the C++ to flatten...

3 minutes read.

Linear Queue Data Structure in C

Data Structure There are many ways to store data in programming, that Queue has features that make it all the more special. We all know that data structure is a way...

9 minutes read.

Find all possible words from board

We have been given a dictionary of words and a board of characters from which we can form strings. Now, we have to check if the string is present in...

5 minutes read.

Rearrange a linked list into alternate fashion first and the last element

Rearrange a linked list into alternate fashion first and the last element This article will explain how to rearrange the linked list into alternate fashion first and the last element. Here,...

3 minutes read.

Quick Sort

Quicksort is a sorting algorithm that uses a divide-and-conquer strategy. A pivot element is used to divide an array into subarrays (element selected from the array).  The pivot element should be...

4 minutes read.