1.23
2.0
main
test-branch
| Line | |
|---|
| 1 | #include <stdio.h>
|
|---|
| 2 | #include <pthread.h>
|
|---|
| 3 |
|
|---|
| 4 | int num;
|
|---|
| 5 |
|
|---|
| 6 | pthread_mutex_t m;
|
|---|
| 7 | pthread_cond_t empty, full;
|
|---|
| 8 |
|
|---|
| 9 | void * thread1(void * arg)
|
|---|
| 10 | {
|
|---|
| 11 | pthread_mutex_lock(&m);
|
|---|
| 12 |
|
|---|
| 13 | while (num > 0)
|
|---|
| 14 | pthread_cond_wait(&empty, &m);
|
|---|
| 15 |
|
|---|
| 16 | num++;
|
|---|
| 17 |
|
|---|
| 18 | pthread_mutex_unlock(&m);
|
|---|
| 19 | pthread_cond_signal(&full);
|
|---|
| 20 | pthread_exit(NULL);
|
|---|
| 21 | }
|
|---|
| 22 |
|
|---|
| 23 |
|
|---|
| 24 | void * thread2(void * arg)
|
|---|
| 25 | {
|
|---|
| 26 | pthread_mutex_lock(&m);
|
|---|
| 27 |
|
|---|
| 28 | while (num == 0)
|
|---|
| 29 | pthread_cond_wait(&full, &m);
|
|---|
| 30 |
|
|---|
| 31 | num--;
|
|---|
| 32 |
|
|---|
| 33 | pthread_mutex_unlock(&m);
|
|---|
| 34 |
|
|---|
| 35 | pthread_cond_signal(&empty);
|
|---|
| 36 | pthread_exit(NULL);
|
|---|
| 37 | }
|
|---|
| 38 |
|
|---|
| 39 |
|
|---|
| 40 | int main()
|
|---|
| 41 | {
|
|---|
| 42 | pthread_t t1, t2;
|
|---|
| 43 |
|
|---|
| 44 | num = 1;
|
|---|
| 45 |
|
|---|
| 46 | pthread_mutex_init(&m, 0);
|
|---|
| 47 | pthread_cond_init(&empty, 0);
|
|---|
| 48 | pthread_cond_init(&full, 0);
|
|---|
| 49 |
|
|---|
| 50 | pthread_create(&t1, 0, thread1, 0);
|
|---|
| 51 | pthread_create(&t2, 0, thread2, 0);
|
|---|
| 52 |
|
|---|
| 53 | pthread_join(t1, 0);
|
|---|
| 54 | pthread_join(t2, 0);
|
|---|
| 55 |
|
|---|
| 56 | if (num!=1)
|
|---|
| 57 | {
|
|---|
| 58 | ERROR: goto ERROR;
|
|---|
| 59 | ;
|
|---|
| 60 | }
|
|---|
| 61 |
|
|---|
| 62 | return 0;
|
|---|
| 63 |
|
|---|
| 64 | }
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.