×

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

Bubble Sort vs Selection Sort

In this article, we will discuss the basic differences between these two sorting algorithms. Let us have a quick overview of what these sorting algorithms are? And what are the...

6 minutes read.

Insertion Sort vs Selection Sort

In this article, we will discuss insertion sort, Selection sort and the basic differences between these two sorting techniques in detail: What is Insertion Sort? Insertion Sort – The insertion sort is...

5 minutes read.

Linear vs Non-Linear: Data Structure

What is Linear Data Structure? The data structure is said to be linear if the data elements are arranged linearly or we can say sequentially. In the linear data structure, the...

3 minutes read.

Linear vs Binary Search: Data Structure

Difference Between Linear and Binary Search What is Linear Search? A linear search also referred as a sequential search. It is a way to find an element within a list and it...

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.

Convert Binary Tree into a Threaded Binary Tree

Implementation /*Writing a C++ program that will help us change the binary tree into a threaded binary tree and help us transform. */ #include <bits/stdc++.h> using namespace std; /*Creating the structure of a node...

11 minutes read.

Extended Binary Tree

A form of binary tree known as an extended binary tree replaces all of the original tree's null subtrees with special nodes known as external nodes, while the remaining nodes...

4 minutes read.

Doubly Linked List

Doubly Linked List Doubly linked list is another kind of Linked list. Doubly linked list contains two pointers for navigation. In this, we can traverse the list in both directions, either...

4 minutes read.

Huffman tree in Data Structures

The Huffman trees in the field of data structures are pretty impressive in their work. They are generally treated as the binary tree, which is linked with the least external...

6 minutes read.

Applications of trees in data structures

Data structures Storage used to organize and store data is known as the data structure. It is a method of managing computerized data to translate or retrieve it more efficiently. A...

7 minutes read.

Optimal binary search tree using dynamic programming

Implementation // We are creating a presentation where we will present a recursive method of the optimal binary search tree problem.  #include <bits/stdc++.h> using namespace std; //creating a utility function that will help us...

9 minutes read.

What is a Height-Balanced Tree in Data Structure

A height-balanced tree is a type of binary tree. If the absolute difference between the heights of the left and right subtree is less than or equal to 1, then...

6 minutes read.

Interval Tree

Interval Tree Interval Tree: The concept is to increase a Binary Search Tree self-balancing such as Red Black Tree, and AVL Tree, so that every feature can be completed in time O(Logn). Each Interval...

4 minutes read.

Sorting Algorithms in Data Structures

A sorting algorithm is used to organize the elements of an array or list. Sorting an array, for example. Unsorted array 572941 Sorted array 124579 We're sorting the array in ascending order right now. This procedure...

4 minutes read.

Cycle sort

Cycle sort is an examination arranging calculation which powers exhibit to be figured into the quantity of cycles where every one of them can be pivoted to create an arranged...

5 minutes read.

Finding the Maximum Element in a Binary Tree

Implementation // Creating a C++ program to excavate the minimum and maximum in a given binary tree. #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new tree node. class __nod { public: int record; __nod *Lft, *Rt; /*...

4 minutes read.

Data Structures Tutorial

The data structure is a way of storing and organizing data in a computer system. So that we can use the data quickly, which means the information is stored and...

7 minutes read.

Operations of B Tree in C++ Language

B tree tends to be a self-aligning and balancing tree that helps us organise our data and document safely. We know that every data or information in the B tree...

9 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Application of 2D array - Sparse Matrix

2D Arrays Application - Sparse Matrix A matrix is a two-dimensional data item consisting of m rows and n columns, with a total of m x n values. A sparse matrix...

7 minutes read.