You are on page 1of 8

Muhammad Sheharyar Raja

201014

BSCYS 7B

Parallel and Distributed Computing

Sir Usama Amir

Question 1:

Part A:

Write a C# program that uses two threads to increment a shared counter. Ensure that the counter is updated

safely without data corruption.

Code:

using System;
using System.Threading;

class Program
{
static int counter = 0;
static object lockObject = new object();

static void Main()


{
// Create two threads
Thread thread1 = new Thread(IncrementCounter);
Thread thread2 = new Thread(IncrementCounter);

// Start the threads


thread1.Start();
thread2.Start();

// Wait for both threads to finish


thread1.Join();
thread2.Join();

Console.WriteLine("Final counter value: " + counter);


}

static void IncrementCounter()


{ // Increment the counter
for (int i = 0; i < 50000; i++)

{
// Lock critical section
lock (lockObject)
{
counter++;
}
}
}
}

ScreenShot:

Part B:

Multi-Client Chat Server

i. Write a C# program containing a multi-client chat server allows multiple clients to connect, send

messages, and receive messages from all other connected clients in a chat room. (client server

communication)

Code

Server:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

public class ChatServer


{
private static readonly List<TcpClient> clients = new List<TcpClient>();

public static void Main(string[] args)


{
var server = new ChatServer();
server.Start();
}
public void Start()
{
var listener = new TcpListener(IPAddress.Any, 8888);
listener.Start();
Console.WriteLine("Server started...");

while (true)
{
TcpClient client = listener.AcceptTcpClient();
lock (clients)
{
clients.Add(client);
}
Task.Run(() => HandleClient(client));
}
}

private void HandleClient(TcpClient client)


{
while (true)
{
byte[] buffer = new byte[1024];
int bytesRead = client.GetStream().Read(buffer, 0, buffer.Length);
if (bytesRead == 0) break;

string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);


BroadcastMessage(message, client);
}

lock (clients)
{
clients.Remove(client);
}
client.Close();
}

private void BroadcastMessage(string message, TcpClient sender)


{
lock (clients)
{
foreach (var client in clients)
{
if (client != sender)
{
client.GetStream().Write(Encoding.ASCII.GetBytes(message));
}
}
}
}
}

Client:

using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

public class ChatClient


{
public static void Main(string[] args)
{
var client = new ChatClient();
client.Start();
}

public void Start()


{
TcpClient tcpClient;
try
{
tcpClient = new TcpClient("127.0.0.1", 8888);
Console.WriteLine("Connected to the server.");

// Start receiving messages


Task.Run(() => ReceiveMessages(tcpClient));

// Start sending messages


while (true)
{
var message = Console.ReadLine();
SendMessage(tcpClient, message);
}
}
catch (SocketException ex)
{
Console.WriteLine($"Error connecting to the server: {ex.Message}");
}
}

private void SendMessage(TcpClient client, string message)


{
if (string.IsNullOrEmpty(message)) return;

try
{
client.GetStream().Write(Encoding.ASCII.GetBytes(message));
}
catch (Exception ex)
{
Console.WriteLine($"Error sending data: {ex.Message}");
}
}

private void ReceiveMessages(TcpClient client)


{
try
{
while (true)
{
byte[] buffer = new byte[1024];
var bytesRead = client.GetStream().Read(buffer, 0, buffer.Length);
if (bytesRead == 0) break;

var receivedMessage = Encoding.ASCII.GetString(buffer, 0, bytesRead);


Console.WriteLine($"Received: {receivedMessage}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error receiving data: {ex.Message}");
}
}
}

Screenshot:
Question 2:

Part A:

Write a program to find and print prime numbers in a given range using OMNeT++.

Code:

using System;

class Program
{
static void Main()
{
Console.Write("Enter the lower bound of the range: ");
int lowerBound = int.Parse(Console.ReadLine());

Console.Write("Enter the upper bound of the range: ");


int upperBound = int.Parse(Console.ReadLine());

Console.WriteLine($"Prime numbers between {lowerBound} and {upperBound} are:");

for (int num = lowerBound; num <= upperBound; num++)


{
if (IsPrime(num))
{
Console.Write(num + " ");
}
}

Console.WriteLine();
}

static bool IsPrime(int number)


{
if (number <= 1)
return false;
if (number <= 3)
return true;
if (number % 2 == 0 || number % 3 == 0)
return false;

for (int i = 5; i * i <= number; i += 6)


{
if (number % i == 0 || number % (i + 2) == 0)
return false;
}
return true;
}
}

Screenshot:

Part B:

Task: Parallel Matrix Addition

i. Write a program that adds two matrices in parallel (using TPL Library).

Code:

using System;
using System.Threading.Tasks;

class Program
{
static void Main()
{
Console.Write("Enter the number of rows: ");
int rows = int.Parse(Console.ReadLine());

Console.Write("Enter the number of columns: ");


int cols = int.Parse(Console.ReadLine());

int[,] matrix1 = new int[rows, cols];


int[,] matrix2 = new int[rows, cols];
int[,] resultMatrix = new int[rows, cols];

Console.WriteLine("Enter elements of Matrix 1:");


InitializeMatrix(matrix1);

Console.WriteLine("Enter elements of Matrix 2:");


InitializeMatrix(matrix2);

// Parallel addition of matrices using TPL


Parallel.For(0, rows, i =>
{
Parallel.For(0, cols, j =>
{
resultMatrix[i, j] = matrix1[i, j] + matrix2[i, j];
});
});

// Display result matrix


Console.WriteLine("Result Matrix:");
PrintMatrix(resultMatrix);
}

static void InitializeMatrix(int[,] matrix)


{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);

for (int i = 0; i < rows; i++)


{
for (int j = 0; j < cols; j++)
{
Console.Write($"Enter element at position [{i},{j}]: ");
matrix[i, j] = int.Parse(Console.ReadLine());
}
}
}

static void PrintMatrix(int[,] matrix)


{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);

for (int i = 0; i < rows; i++)


{
for (int j = 0; j < cols; j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
}

Screenshot:

You might also like