source:
CIVL/examples/concurrency/dining.cvl@
8d298d8
| Last change on this file since 8d298d8 was e6b02c8, checked in by , 12 years ago | |
|---|---|
|
|
| File size: 1.1 KB | |
| Rev | Line | |
|---|---|---|
| [72c01cc] | 1 | /* Dining philosophers with fork switching. Even philosophers pick |
| 2 | * up left fork first, odd pick up right first. This breaks deadlock. | |
| 3 | * | |
| [69bf2e6] | 4 | * civl verify -inputBOUND=4 dining.cvl |
| [72c01cc] | 5 | */ |
| [e6b02c8] | 6 | #include <civlc.cvh> |
| [793cfc2] | 7 | |
| [69bf2e6] | 8 | $input int BOUND; // upper bound on number of philosophers |
| [72c01cc] | 9 | $input int n; // number of philosophers |
| [69bf2e6] | 10 | $assume 2<=n && n<=BOUND; |
| [72c01cc] | 11 | |
| [1de5580] | 12 | // Each fork will be on the table (-1) or in a hand (0-(n-1)). |
| [72c01cc] | 13 | int forks[n]; |
| [793cfc2] | 14 | |
| 15 | void dine(int id) { | |
| 16 | int left = id; | |
| 17 | int right = (id + 1) % n; | |
| [72c01cc] | 18 | |
| 19 | while (1) { | |
| [793cfc2] | 20 | if (id % 2 == 0) { |
| [1de5580] | 21 | $when (forks[left] < 0) {forks[left] = id;} |
| 22 | $when (forks[right] < 0) {forks[right] = id;} | |
| 23 | forks[right] = -1; | |
| 24 | forks[left] = -1; | |
| [793cfc2] | 25 | } else { |
| [1de5580] | 26 | $when (forks[right] < 0) {forks[right] = id;} |
| 27 | $when (forks[left] < 0) {forks[left] = id;} | |
| 28 | forks[right] = -1; | |
| 29 | forks[left] = -1; | |
| [793cfc2] | 30 | } |
| [05ae5d1] | 31 | } |
| [793cfc2] | 32 | } |
| 33 | ||
| [72c01cc] | 34 | /* Put all forks on the table. */ |
| [793cfc2] | 35 | void init() { |
| [1de5580] | 36 | for (int i = 0; i < n; i++) forks[i] = -1; |
| [793cfc2] | 37 | } |
| 38 | ||
| 39 | void main() { | |
| 40 | $proc philosophers[n]; | |
| [48bfab9] | 41 | |
| [17f5ed1] | 42 | init(); |
| 43 | for (int i = 0; i < n; i++) | |
| 44 | philosophers[i] = $spawn dine(i); | |
| [48bfab9] | 45 | for (int i = 0; i < n; i++) |
| 46 | $wait(philosophers[i]); | |
| [793cfc2] | 47 | } |
Note:
See TracBrowser
for help on using the repository browser.
