0% found this document useful (0 votes)
13 views10 pages

Name: M.V.S.Sai Roshan Class: Cse-A ROLL NO: CH - EN.U4CSE21037

The document describes implementing three clock synchronization algorithms: Lamport logical clocks, vector clocks, and Berkeley's algorithm. For each algorithm, it provides the procedure, source code implementation, and sample output. Lamport's algorithm synchronizes processes using message passing timestamps. Vector clocks assign vector timestamps to events to capture causality. Berkeley's algorithm uses a centralized clock server and slave clients to periodically synchronize clocks.

Uploaded by

dineshvardhan339
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views10 pages

Name: M.V.S.Sai Roshan Class: Cse-A ROLL NO: CH - EN.U4CSE21037

The document describes implementing three clock synchronization algorithms: Lamport logical clocks, vector clocks, and Berkeley's algorithm. For each algorithm, it provides the procedure, source code implementation, and sample output. Lamport's algorithm synchronizes processes using message passing timestamps. Vector clocks assign vector timestamps to events to capture causality. Berkeley's algorithm uses a centralized clock server and slave clients to periodically synchronize clocks.

Uploaded by

dineshvardhan339
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

NAME: M.V.S.

SAI ROSHAN
CLASS: CSE-A
ROLL NO: CH.EN.U4CSE21037
LAB-04

AIM: Perform a study of physical and logical clocks and implement following clocks to perform
synchronization.
1. LAMPORT:
PROCEDURE:
1. Initialize logical clocks for each process in `e1` and `e2`.
2. When a process in `e1` sends a message to `e2`, update the logical clock of the receiving
process.
3. Increment logical clocks for processes in `e2` not involved in the message exchange.
4. When a process in `e1` receives a message from `e2`, update the logical clock of the
receiving process.
5. Increment logical clocks for processes in `e1` not involved in the message exchange.
6. Use the matrix `m` to represent communication events between processes.
7. Display the logical clocks for processes in both sets `e1` and `e2` to observe the ordering
of events.
SOURCE CODE:
def max1(a, b) :
if a > b :
return a
else :
return b
def display(e1, e2, p1, p2) :
print()
print("The time stamps of events in P1:")
for i in range(0, e1) :
print(p1[i], end = " ")
print()
print("The time stamps of events in P2:")
for i in range(0, e2) :
print(p2[i], end = " ")
def lamportLogicalClock(e1, e2, m) :
p1 = [0]*e1
p2 = [0]*e2
for i in range (0, e1) :
p1[i] = i + 1
for i in range(0, e2) :
p2[i] = i + 1
for i in range(0, e2) :
print(end = '\t')
print("e2", end = "")
print(i + 1, end = "")
for i in range(0, e1) :
print()
print("e1", end = "")
print(i + 1, end = "\t")
for j in range(0, e2) :
print(m[i][j], end = "\t")
for i in range(0, e1) :
for j in range(0, e2) :
if(m[i][j] == 1) :
p2[j] = max1(p2[j], p1[i] + 1)
for i in range(j + 1, e2) :
p2[k] = p2[k - 1] + 1
if(m[i][j] == -1) :
p1[i] = max1(p1[i], p2[j] + 1)
for k in range(i + 1, e1) :
p1[k] = p1[k - 1] + 1
display(e1, e2, p1, p2)
if __name__ == "__main__" :
e1 = 5
e2 = 3
m = [[0]*3 for i in range(0,5)]
m[0][0] = 0
m[0][1] = 0
m[0][2] = 0
m[1][0] = 0
m[1][1] = 0
m[1][2] = 1
m[2][0] = 0
m[2][1] = 0
m[2][2] = 0
m[3][0] = 0
m[3][1] = 0
m[3][2] = 0
m[4][0] = 0
m[4][1] = -1
m[4][2] = 0
lamportLogicalClock(e1, e2, m)
OUTPUT:

2. VECTOR CLOCK
PROCEDURE:
1. Initialize a vector clock array V with N logical clocks, one for each process.
2. When an event occurs in process P_i, increment its logical clock V[i].
3. Include the vector clock with outgoing messages: send V along with the message.
4. On receiving a message with vector clock V', update the local vector clock V as follows:
V[i] = max(V[i], V'[i]) for all i in range(N).
5. When an event occurs concurrently in multiple processes, increment the logical clock of
the current process: V[i] += 1.
6. Use the vector clock to establish a partial ordering of events: Event A happened before
Event B if V[A] <= V[B] for all i.
7. Detect causality violations: If V[A] > V[B] for some i, then Event A happened after Event B
in process P_i.
SOURCE CODE:
def vector_compare(vector1,vector2):
vector = [max(value) for value in zip(vector1,vector2)]
return vector
P = {1:{}, 2:{}, 3:{}}
inc = 0
n1 = int(input("Enter the no. of events in Process 1 : "))
e1 = [i for i in range(1, n1 + 1)]
P[1] = {key: [inc + key, 0, 0] for key in e1}
print(P[1])
print("\n")
n2 = int(input("Enter the no. of events in Process 2 : "))
e2 = [i for i in range(1, n2 + 1)]
P[2] = {key: [0, inc + key, 0] for key in e2}
print(P[2])
print("\n")
n3 = int(input("Enter the no. of events in Process 3 : "))
e3 = [i for i in range(1, n3 + 1)]
P[3] = {key: [0, 0, inc + key] for key in e3}
print(P[3])
print("\n")
comm = int(input("Enter the no of communication lines : "))
print("\n")
while inc < comm:
sent = int(input("Enter the sending process number : "))
recv = int(input("Enter the receiving process number : "))
sent_event_no = int(input("Enter the sending event number : "))
recv_event_no = int(input("Enter the receiving event number : "))
if sent <= 3 and recv <= 3:
print ("P{} --> P{}".format(sent,recv))
new_vector = vector_compare(P[sent][sent_event_no],P[recv][recv_event_no])
P[recv][recv_event_no] = new_vector
print ("New vector value of \"event {}\" in process P{} is : {}
\n".format(recv_event_no,recv,P[recv][recv_event_no]))
if (recv_event_no + 1) in P[recv]:
for i in range(recv_event_no + 1, len(P[recv]) + 1):
P[recv][i] = vector_compare(P[recv][i-1],P[recv][i])
else:
print ("Enter the sent/recv within existing process")
inc += 1
print("Final vectors of the 3 process are")
print(P[1])
print(P[2])
print(P[3])
OUTPUT:

3. BERKELEY’S ALGORITHM
PROCEDURE:
Clockserver.py
1. Create a clock server socket and bind it to a specified port.
2. Start a thread to accept incoming connections from clients (slaves).
3. In the connected thread, continuously receive clock time from the client and update the
client data structure.
4. In a separate thread, initiate clock synchronization cycles at regular intervals.
5. Calculate the average clock difference among all connected clients.
6. For each client, send the synchronized time based on the average clock difference.
7. Repeat the synchronization cycle periodically, maintaining a parallel process for accepting
connections.
SOURCE CODE:
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)
Client.py
1. Create a client socket and connect it to the clock server at a specified port.
2. Start a thread to continuously send the current time to the server.
3. Start another thread to continuously receive the synchronized time from the server.
4. The sending thread encodes the current time as a string and sends it to the server.
5. The receiving thread decodes the synchronized time from the server and prints it.
6. Repeat the sending and receiving processes continuously in parallel threads.
7. The client interacts with the clock server for time synchronization.
SOURCE CODE:
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:

RESULT:
The physical clock, vector clock and Berkeley’s algorithm were executed successfully using python.

You might also like