summaryrefslogtreecommitdiffstats
path: root/pthread1.c
blob: c7e63038dae986bb7ee2fa350bd872f9b3c3d5b2 (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
93
94
95
96
97
98
99
100
101
102
103
/* extreme case */

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

int left = 500, right = 500;
pthread_mutex_t lock, cond_lock;
pthread_cond_t cond;
pthread_barrier_t barrier;

void *leftf(void *args)
{
    sleep(3);
    
    pthread_barrier_wait(&barrier);
    printf("Left passed barrier\n");
    sleep(3);

    while (1)
    {
        struct timeval tv;
        struct timespec ts;
        gettimeofday(&tv,  NULL);
        ts.tv_sec = tv.tv_sec + 1;
        ts.tv_nsec = 0;

        pthread_mutex_lock(&cond_lock);
        pthread_cond_timedwait(&cond, &cond_lock, &ts);
        pthread_mutex_unlock(&cond_lock);

        pthread_mutex_lock(&lock);
        printf("Now running left\n");

        int i;
        for (i = 0; i < 250; i++)
        {
            if (right > 0)
            {
                left++;
                right--;
            }
            usleep(10000);
        }

        pthread_mutex_unlock(&lock);
        pthread_cond_signal(&cond);
    }
}

void *rightf(void *args)
{
    pthread_barrier_wait(&barrier);
    printf("Right passed barrier\n");

    while (1)
    {
        pthread_mutex_lock(&lock);
        printf("Now running right\n");

        int i;
        for (i = 0; i < 250; i++)
        {
            if (left > 0)
            {
                right++;
                left--;
            }
            usleep(10000);
        }

        pthread_mutex_unlock(&lock);
        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(&lock, 0);
    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;
}