Last change
on this file since 400 was 2, checked in by Rick van der Zwet, 15 years ago |
Initial import of data of old repository ('data') worth keeping (e.g. tracking
means of URL access statistics)
|
File size:
1.1 KB
|
Rev | Line | |
---|
[2] | 1 |
|
---|
| 2 |
|
---|
| 3 | #include <sysexits.h>
|
---|
| 4 | #include <stdlib.h>
|
---|
| 5 | #include <pthread.h>
|
---|
| 6 | #include <stdio.h>
|
---|
| 7 | #include <unistd.h>
|
---|
| 8 |
|
---|
| 9 |
|
---|
| 10 | static int x = 0;
|
---|
| 11 | static int y = 0;
|
---|
| 12 |
|
---|
| 13 | static int flagA = 0;
|
---|
| 14 | static int flagB = 0;
|
---|
| 15 | static int turn = 0;
|
---|
| 16 |
|
---|
| 17 |
|
---|
| 18 | //Consumer
|
---|
| 19 | void *procA() {
|
---|
| 20 | for ( ;; ) {
|
---|
| 21 | //hungry, ask cheff to prepare something
|
---|
| 22 | flagA = 1;
|
---|
| 23 | turn = 1;
|
---|
| 24 | while ( flagB && turn == 1 ) { usleep(1); }
|
---|
| 25 | //eat
|
---|
| 26 | printf("Turn A\n");
|
---|
| 27 | y = 0;
|
---|
| 28 | flagA = 0;
|
---|
| 29 |
|
---|
| 30 |
|
---|
| 31 |
|
---|
| 32 | }
|
---|
| 33 | pthread_exit(NULL);
|
---|
| 34 | }
|
---|
| 35 |
|
---|
| 36 | //Producer
|
---|
| 37 | void *procB() {
|
---|
| 38 | for ( ;; ) {
|
---|
| 39 | //prepare food, and allow eating
|
---|
| 40 | flagB = 1;
|
---|
| 41 | turn = 0;
|
---|
| 42 | while ( flagA && turn == 0 ) { usleep(1); }
|
---|
| 43 | printf("Turn B\n");
|
---|
| 44 | y = 1;
|
---|
| 45 | flagB = 0;
|
---|
| 46 | }
|
---|
| 47 | pthread_exit(NULL);
|
---|
| 48 | }
|
---|
| 49 |
|
---|
| 50 |
|
---|
| 51 | int main (int argc, char * argv[]) {
|
---|
| 52 |
|
---|
| 53 | //create 2 threads
|
---|
| 54 | pthread_t thread0, thread1;
|
---|
| 55 | pthread_create(&thread0, NULL, procA, NULL);
|
---|
| 56 | pthread_create(&thread1, NULL, procB, NULL);
|
---|
| 57 |
|
---|
| 58 | //debugging
|
---|
| 59 | for ( ;; ) {
|
---|
| 60 | printf("flagA:%i flagB:%i turn:%i, y:%i\n", flagA, flagB, turn, y);
|
---|
| 61 | sleep(1);
|
---|
| 62 | }
|
---|
| 63 | pthread_exit(NULL);
|
---|
| 64 | return(EX_OK);
|
---|
| 65 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.