summaryrefslogtreecommitdiffstats
path: root/pthread3.c
blob: 3a2f86ee40ad064c9718cc4036cffb80ecc9bea2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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;
}