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

int n;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void*
fnO(void* arg)
{
    int xrand;
    int count = 0;

    while (1) {
        usleep(200 * 1000);
        do {
            xrand = rand();
        } while ((xrand % 2) == 1);

        count++;
        pthread_mutex_lock(&mutex);
        printf("Thread O, count = %d, old x = %d, x = %d, even = %d\n", count, n, n+xrand, ((n+xrand) % 2)==0);
        n += xrand;

        if ((count == 1000) || (count >= 10 && (n%2) == 0)) {
            pthread_mutex_unlock(&mutex);
            break;
        }
        pthread_mutex_unlock(&mutex);

    }

    printf("Thread O terminated.\n");
    pthread_exit(NULL);
}

void*
fnE(void* arg)
{
    int xrand;
    int count = 0;

    while (1) {
        usleep(200 * 1000);
        do {
            xrand = rand();
        } while ((xrand % 2) == 0);

        count++;
        pthread_mutex_lock(&mutex);
        printf("\tThread E, count = %d, old x = %d, x = %d, odd = %d\n", count, n, n+xrand, ((n+xrand) % 2)==1);
        n += xrand;

        if ((count == 1000) || (count >= 10 && (n%2) == 1)) {
            pthread_mutex_unlock(&mutex);
            break;
        }
        pthread_mutex_unlock(&mutex);
    }

    printf("\tThread E terminated.\n");
    pthread_exit(NULL);
}

int
main()
{
    pthread_t tO, tE;
    srand(time(NULL));
    n = 0;

    pthread_create(&tO, NULL, &fnO, NULL);
    pthread_create(&tE, NULL, &fnE, NULL);

    pthread_join(tO, NULL);
    pthread_join(tE, NULL);

    return 0;
}