Skip to content

Instantly share code, notes, and snippets.

View aerodame's full-sized avatar

Steve Dame aerodame

View GitHub Profile
public class Process {
private String name;
public Process() {
}
public Process(String name) {
this.name = name;
}
public class Worker extends Thread {
private final Semaphore semaphore;
ConcurrentHashMap<Integer, String> sharedCalculatedFactorials;
public Worker(String name, Semaphore semaphore, ConcurrentHashMap<Integer, String> factorialsHashMap) {
super(name);
this.semaphore = semaphore;
this.sharedCalculatedFactorials = factorialsHashMap;
}
public class Semaphore {
private int S;
private Queue<Process> list; // Use a Queue to represent the process list
public Semaphore(int permits) {
this.S = permits;
this.list = new LinkedList<>(); // Initialize the process list
}
public synchronized void P(Process process) { // "P" operation (wait/acquire)
class SimpleSemaphore {
private int S;
public SimpleSemaphore(int initialPermits) {
this.S = initialPermits;
}
public synchronized void acquire() throws InterruptedException {
while (S <= 0) {
wait(); // Block until a permit is available
#include "MutexSemaphore.h"
Semaphore::Semaphore(int initialValue) : S(initialValue) {}
void Semaphore::P() {
std::unique_lock<std::mutex> lock(mutex_); // Acquire mutex
cv_.wait(lock, [this] { return S > 0; }); // Wait until S > 0
S--;
}
#include "SimpleSemaphore.h"
Semaphore::Semaphore(int initialValue) : S(initialValue) {}
void Semaphore::P() {
while (S <= 0) {
// Busy wait (not ideal for real-world scenarios)
}
S--;
}
// j = 1-i ; i=0, j=1
// Process Pi
Pi() {
flag[i] = true;
turn = j;
// entry section
while (flag[j] && turn == j); // Busy wait
// Critical Section
public class OSTask_MFQSTest {
final int default_sleep_time = 10;
final long default_join_wait_time = 1000L;
final long default_burst_duration = 1000L;
final Map<String, Long[]> taskData = new HashMap<>();
{ // Use an initializer block to populate the map
taskData.put("Task A", new Long[]{0L, 5000L});
taskData.put("Task B", new Long[]{0L, 1000L});
taskData.put("Task C", new Long[]{0L, 3000L});
public class OSTask_RRTest {
final int default_sleep_time = 10;
final long default_join_wait_time = 1000L;
final long default_burst_duration = 1000L;
final Map<String, Long[]> taskData = new HashMap<>();
{ // Use an initializer block to populate the map
taskData.put("Task A", new Long[]{0L, 5000L});
taskData.put("Task B", new Long[]{0L, 1000L});
taskData.put("Task C", new Long[]{0L, 3000L});
public class OSTaskFCFSTest {
private final Random random = new Random();
@Test
@Timeout(value = 60, unit = TimeUnit.SECONDS) // Set a timeout for the test
public void testFCFSScheduling() throws InterruptedException {
Queue<OSTask> taskQueue = new LinkedList<>();
// Create 5 tasks with unique random burst times between 1 and 5 seconds
Set<Long> burstTimes = new HashSet<>(); // Use a Set to ensure unique burst times
for (char taskName = 'A'; taskName <= 'E'; taskName++) {