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

int x = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void*
fn(void* arg)
{
    char* thread_name = (char*) arg;
    int xrand;
    long hit;

    hit = 0;
    while (1) {
        xrand = rand() % 1000;
        usleep(xrand);

        pthread_mutex_lock(&mutex);
        if (x > 500) {
            printf("I'm the thread %s with hit = '%ld' and x = '%d'\n", thread_name, hit, x);
            pthread_mutex_unlock(&mutex);
            break;
        }
        x++;
        pthread_mutex_unlock(&mutex);

        hit++;
    }

    pthread_exit((void*) hit);
}

int
main()
{
    pthread_t tA, tB;
    void *result1, *result2;
    long total;
    srand(time(NULL));

    pthread_create(&tA, NULL, &fn, (void*) "A");
    pthread_create(&tB, NULL, &fn, (void*) "B");

    pthread_join(tA, &result1);
    pthread_join(tB, &result2);

    total = (long) result1 + (long) result2;
    printf("Total = %ld + %ld = %ld'\n", (long) result1, (long) result2, total);
    return 0;
}