Hardware Reference
In-Depth Information
public class m {
final public static int BUF SIZE = 100; // buffer runs from 0 to 99
final public static long MAX PRIME= 100000000000L; // stop here
public static int in = 0, out = 0;
// pointers to the data
public static long buffer[]=newlong[BUF SIZE];
// primes stored here
public static producer p;
// name of the producer
public static consumer c;
// name of the consumer
public static int filled = 0, available = 100;
// semaphores
public static void main(String args[ ]) {
// main class
p = new producer( );
// create the producer
c = new consumer( );
// create the consumer
p.start( );
// start the producer
c.start( );
// start the consumer
}
// This is a utility function for circularly incrementing in and out
public static int next(int k) {if (k < BUF SIZE
1) return(k+1); else return(0);}
}
class producer extends Thread {
// producer class
native void up(int s); native void down(int s);
// methods on semaphores
public void run( ) {
// producer code
long prime = 2;
// scratch variable
while (prime < m.MAX PRIME) {
prime = next prime(prime);
// statement P1
down(m.available);
// statement P2
m.buffer[m.in] = prime;
// statement P3
m.in = m.next(m.in);
// statement P4
up(m.filled);
// statement P5
}
}
private long next prime(long prime){ ... }
// function that computes next prime
}
class consumer extends Thread {
// consumer class
native void up(int s); native void down(int s);
// methods on semaphores
public void run( ) {
// consumer code
long emirp = 2;
// scratch variable
while (emirp < m.MAX PRIME) {
down(m.filled);
// statement C1
emirp = m.buffer[m.out];
// statement C2
m.out = m.next(m.out);
// statement C3
up(m.available);
// statement C4
System.out.println(emirp);
// statement C5
}
}
}
Figure 6-29. Parallel processing using semaphores.
 
Search WWH ::




Custom Search