diff options
Diffstat (limited to 'pthread2.c')
-rw-r--r-- | pthread2.c | 89 |
1 files changed, 89 insertions, 0 deletions
diff --git a/pthread2.c b/pthread2.c new file mode 100644 index 0000000..701721b --- /dev/null +++ b/pthread2.c @@ -0,0 +1,89 @@ +/* simple */ + +#include <stdlib.h> +#include <stdio.h> +#include <pthread.h> +#include <unistd.h> + +int left = 500, right = 500; +pthread_mutex_t cond_lock; +pthread_cond_t cond; +pthread_barrier_t barrier; + +void *leftf(void *args) +{ + pthread_barrier_wait(&barrier); + printf("Left passed barrier\n"); + + while (1) + { + pthread_mutex_lock(&cond_lock); + pthread_cond_wait(&cond, &cond_lock); + pthread_mutex_unlock(&cond_lock); + + printf("Now running left\n"); + + int i; + for (i = 0; i < 250; i++) + { + if (right > 0) + { + left++; + right--; + } + usleep(10000); + } + + pthread_cond_signal(&cond); + } +} + +void *rightf(void *args) +{ + pthread_barrier_wait(&barrier); + printf("Right passed barrier\n"); + + while (1) + { + printf("Now running right\n"); + + int i; + for (i = 0; i < 250; i++) + { + if (left > 0) + { + right++; + left--; + } + usleep(10000); + } + + pthread_cond_signal(&cond); + + pthread_mutex_lock(&cond_lock); + pthread_cond_wait(&cond, &cond_lock); + pthread_mutex_unlock(&cond_lock); + } +} + +int main(int argc, char **argv) +{ + pthread_t thread1, thread2; + + pthread_mutex_init(&cond_lock, 0); + pthread_cond_init(&cond, 0); + pthread_barrier_init(&barrier, 0, 2); + + pthread_create(&thread2, 0, rightf, 0); + pthread_create(&thread1, 0, leftf, 0); + + int i; + for (i = 0; i < 1000; i++) + { + printf("%d+%d = %d\n", left, right, left+right); + usleep(100000); + } + + return 0; +} + |