forked from gatsbyd/mit_6.828_jos_2018
-
Notifications
You must be signed in to change notification settings - Fork 0
/
primes.c
53 lines (44 loc) · 1.1 KB
/
primes.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Concurrent version of prime sieve of Eratosthenes.
// Invented by Doug McIlroy, inventor of Unix pipes.
// See http://swtch.com/~rsc/thread/.
// The picture halfway down the page and the text surrounding it
// explain what's going on here.
//
// Since NENV is 1024, we can print 1022 primes before running out.
// The remaining two environments are the integer generator at the bottom
// of main and user/idle.
#include <inc/lib.h>
unsigned
primeproc(void)
{
int i, id, p;
envid_t envid;
// fetch a prime from our left neighbor
top:
p = ipc_recv(&envid, 0, 0);
cprintf("CPU %d: %d ", thisenv->env_cpunum, p);
// fork a right neighbor to continue the chain
if ((id = fork()) < 0)
panic("fork: %e", id);
if (id == 0)
goto top;
// filter out multiples of our prime
while (1) {
i = ipc_recv(&envid, 0, 0);
if (i % p)
ipc_send(id, i, 0, 0);
}
}
void
umain(int argc, char **argv)
{
int i, id;
// fork the first prime process in the chain
if ((id = fork()) < 0)
panic("fork: %e", id);
if (id == 0)
primeproc();
// feed all the integers through
for (i = 2; ; i++)
ipc_send(id, i, 0, 0);
}