Reputation: 1
Firstly I think this probably more of a problem with my design and my lack of knowledge for what terms I should be searching for. On to the problem.
Say I have 3 threads (t1, t2, t3).
These threads have access to a thread that implements a semaphore(sem) with 1 permit and is fair (giving FIFO to threads that queue), and a thread that implements a timer (timer) which increments a int (time) every 20ms.
If all 3 threads arrived here in their code at the same time and waited for the timer to increment 6 units before continuing.
//In a thread t_ class
int timeInitial = timer.getTime();
while((timeInitial+6)>timer.getTime()) {
//Sleeps for 10ms to ensure it doesn't miss the timers 20ms
increments
try {
sleep(10);
}
catch (InterruptedException e) {
}
}
//Thread joins queue for the singular permit
sem.aquire();
//In the sem class
public void acquire() {
try {
semaphore.acquire();
}
catch (InterruptedException e) {
}
}
//In the timer class, timer functionality. Also has get and set method for time
@Override
public void run() {
while(processes > 0) {
try {
sleep(21);
time++;
}
catch (InterruptedException e) {
}
}
}
What I would like to happen is if multiple threads attempt to acquire a permit at the same timer time they would in attempt to in order of lowest to highest (t1, t2, t3). Where now they would join the queue in a seemingly random order.
Note, that if say t2 and t3 were already queued for the permit at time=6 and t1 came at time=7, it would not jump the queue but only compare with other additions at time=7 before queuing (t2, t3, t1).
I'm not bound to use a semaphore here, is just my best knowledge of tools to approach this problem.
Upvotes: 0
Views: 312
Reputation: 998
I think you want to have your threads go into a priority queue, which will be sorted by arrival time, then priority when the time is the same. Once a thread adds itself to this priority queue, it enters a wait(). You would need a mechanism that would, at the right time, wake up all threads in the queue. On waking up, they would each check to see whether they are the head of the queue - the ones that are not, go back to wait(), and the one that is, removes itself from the queue and goes and does its thing. Maybe the right time is each time the thread that was selected completes its work, or goes back into the queue?
Upvotes: 1