summaryrefslogtreecommitdiff
path: root/Year_3/TSDWL/ex_20131219/thread.c
blob: e46d05b35e52528d6ba07462222bb49c2344e25b (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
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int m;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond;

void*
fn_t1(void* arg)
{
    int xrand;

    while (1) {
        pthread_mutex_lock(&mutex);
        if (m >= 1 && m <= 5) {
            xrand = (rand() % 10) + 1;
            printf("Thread 1: (%d, %d)\n", m, xrand);
            m = xrand;
            pthread_cond_broadcast(&cond);
            pthread_mutex_unlock(&mutex);
        } else {
            pthread_mutex_unlock(&mutex);
            pthread_cond_wait(&cond, &mutex);
        }
    }

    pthread_exit(NULL);
}

void*
fn_t2(void* arg)
{
    int xrand;

    while (1) {
        pthread_mutex_lock(&mutex);
        if (m >= 6 && m <= 10) {
            xrand = (rand() % 10) + 1;
            printf("Thread 2: (%d, %d)\n", m, xrand);
            m = xrand;
            pthread_cond_broadcast(&cond);
            pthread_mutex_unlock(&mutex);
        } else {
            pthread_mutex_unlock(&mutex);
            pthread_cond_wait(&cond, &mutex);
        }
    }

    pthread_exit(NULL);
}

int
main()
{
    pthread_t th[2];
    srand(time(NULL));
    m = (rand() % 10) + 1;

    pthread_create(&th[0], NULL, (void*)&fn_t1, NULL);
    pthread_create(&th[1], NULL, (void*)&fn_t2, NULL);
    pthread_join(th[0], NULL);
    pthread_join(th[1], NULL);

    return 0;
}