Assignment3 SC
Assignment3 SC
Concurrency
Name CMS ID
Asna Maqsood 426990
Muhammad Owais Khan 404262
Umar Farooq 406481
Zainab Athar 405094
Contents
Concurrency Attainment in Software Systems..............................................................1
Web Servers............................................................................................................... 1
Database Systems...................................................................................................... 4
Batch Processing Systems.......................................................................................... 6
Microservices Architecture......................................................................................... 9
Operating Systems................................................................................................... 13
Distributed Systems................................................................................................. 16
Video/Graphics Rendering Systems..........................................................................19
Simulation Software................................................................................................. 22
Real-Time Communication Systems.........................................................................24
Containers and Virtualization Systems.....................................................................27
app = Flask(__name__)
def handle_request(client_id):
# Simulate processing time
print(f"Processing request from Client {client_id}")
import time
time.sleep(2)
print(f"Completed request from Client {client_id}")
@app.route('/process', methods=['GET'])
def process_request():
client_id = request.args.get('client_id', 'unknown')
thread = threading.Thread(target=handle_request, args=(client_id,))
thread.start()
return f"Request from Client {client_id} is being processed!"
if __name__ == '__main__':
app.run(threaded=True) # Enable multithreading
server.listen(3000, () => {
console.log('Server is listening on port 3000');
});
-- Transaction 1
START TRANSACTION;
SELECT balance FROM accounts WHERE account_id = 1 FOR UPDATE; -- Exclusive lock
UPDATE accounts SET balance = balance - 500 WHERE account_id = 1;
COMMIT;
-- Transaction 2
START TRANSACTION;
SELECT balance FROM accounts WHERE account_id = 1 FOR UPDATE; -- Waits until Transaction 1 is
committed
UPDATE accounts SET balance = balance + 500 WHERE account_id = 2;
COMMIT;
-- Transaction 1: Sets an isolation level
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
START TRANSACTION;
SELECT balance FROM accounts WHERE account_id = 1;
def compute_payroll(employee_id):
print(f"Processing payroll for employee {employee_id}")
# Simulate computation
return f"Payroll computed for employee {employee_id}"
if __name__ == "__main__":
employees = [101, 102, 103, 104, 105]
# Show results
employee_df.show()
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
"public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {" (“Testing
your Hadoop program with Maven on IntelliJ - Medium”)
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException,
InterruptedException { (“WordCount.java - GitHub”)
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
version: '3.8'
services:
order-service:
image: order-service:latest
ports:
- "8081:8081"
depends_on:
- db
payment-service:
image: payment-service:latest
ports:
- "8082:8082"
depends_on:
- db
notification-service:
image: notification-service:latest
ports:
- "8083:8083"
db:
image: postgres:latest
environment:
POSTGRES_USER: admin
POSTGRES_PASSWORD: secret
import pika
def send_message():
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# Publish a message
message = "New order received"
channel.basic_publish(exchange='', routing_key='order_queue', body=message)
print(f"Sent: {message}")
connection.close()
if __name__ == "__main__":
send_message()
import pika
def receive_message():
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# Consume messages
channel.basic_consume(queue='order_queue', on_message_callback=callback, auto_ack=True)
if __name__ == "__main__":
receive_message()
import org.apache.kafka.clients.producer.*;
import java.util.Properties;
producer.close();
}
}
import org.apache.kafka.clients.consumer.*;
import java.util.Collections;
import java.util.Properties;
while (true) {
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records) {
System.out.printf("Received event: %s%n", record.value());
}
}
}
}
import time
int main() {
// Set up the interrupt handler for SIGINT (Ctrl+C)
signal(SIGINT, handle_interrupt);
return 0;
}
from pyspark import SparkContext
class RaftNode:
def __init__(self, id):
self.id = id
self.state = "follower"
self.votes = 0
def start(self):
print(f"Node {self.id} started as {self.state}.")
while True:
if self.state == "follower":
# Simulating election timeout
time.sleep(random.uniform(1, 3))
self.state = "candidate"
self.votes = 1
print(f"Node {self.id} became a candidate and started election.")
self.elect_leader()
def elect_leader(self):
# Simulating voting process in Raft
if random.choice([True, False]): # Random decision to vote
print(f"Node {self.id} voted for a leader.")
self.votes += 1
if self.votes > 2: # Assume 3 nodes for simplicity
self.state = "leader"
print(f"Node {self.id} became the leader.")
def render_video(total_frames):
# Create a pool of processes to render the frames concurrently
with multiprocessing.Pool(processes=4) as pool:
pool.map(render_frame, range(total_frames))
int main() {
int width = 1920;
int height = 1080;
int image_size = width * height * sizeof(int);
int *d_image;
// Clean up
cudaFree(d_image);
delete[] h_image;
return 0;
}
import time
import multiprocessing
def simulate_traffic(total_vehicles):
# Create a pool of processes to simulate vehicle movements concurrently
with multiprocessing.Pool(processes=4) as pool:
pool.map(simulate_vehicle, range(total_vehicles))