summaryrefslogtreecommitdiffstats
path: root/pthread3.c
diff options
context:
space:
mode:
Diffstat (limited to 'pthread3.c')
-rw-r--r--pthread3.c92
1 files changed, 92 insertions, 0 deletions
diff --git a/pthread3.c b/pthread3.c
new file mode 100644
index 0000000..51fadac
--- /dev/null
+++ b/pthread3.c
@@ -0,0 +1,92 @@
+/* with array */
+
+#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);
+ }
+ sleep(3);
+
+ 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 threads[64], thread2;
+
+ pthread_mutex_init(&cond_lock, 0);
+ pthread_cond_init(&cond, 0);
+ pthread_barrier_init(&barrier, 0, 2);
+
+ pthread_create(&thread2, 0, rightf, 0);
+
+ int i;
+ for (i = 0; i < 64; i++)
+ pthread_create(&threads[i], 0, leftf, 0);
+
+ for (i = 0; i < 1000; i++)
+ {
+ printf("%d+%d = %d\n", left, right, left+right);
+ usleep(100000);
+ }
+
+ return 0;
+}
+