summaryrefslogtreecommitdiff
path: root/tests/bionic/libc/bionic/test_pthread_cond.c
blob: a29111e7c3b7eca9bcb990a44b55507d96486f35 (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
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>


static pthread_cond_t cond1;
static pthread_cond_t cond2;
static pthread_mutex_t test_lock = PTHREAD_MUTEX_INITIALIZER;

static void *
thread1_func(void* arg)
{
    printf("Thread 1 (arg=%p tid=%d) entered.\n", arg, gettid());
    printf("1 waiting for cond1\n");
    pthread_mutex_lock(&test_lock);
    pthread_cond_wait(&cond1, &test_lock );
    pthread_mutex_unlock(&test_lock);
    printf("Thread 1 done.\n");
    return 0;
}

static void *
thread2_func(void* arg)
{
    printf("Thread 2 (arg=%p tid=%d) entered.\n", arg, gettid());
    printf("2 waiting for cond2\n");
    pthread_mutex_lock(&test_lock);
    pthread_cond_wait(&cond2, &test_lock );
    pthread_mutex_unlock(&test_lock);

    printf("Thread 2 done.\n");
    return 0;
}

static void *
thread3_func(void* arg)
{
    printf("Thread 3 (arg=%p tid=%d) entered.\n", arg, gettid());
    printf("3 waiting for cond1\n");
    pthread_mutex_lock(&test_lock);
    pthread_cond_wait(&cond1, &test_lock );
    pthread_mutex_unlock(&test_lock);
    printf("3 Sleeping\n");
    sleep(2);
    printf("3 signal cond2\n");
    pthread_cond_signal(&cond2);

    printf("Thread 3 done.\n");
    return 0;
}

static void *
thread4_func(void* arg)
{
    printf("Thread 4 (arg=%p tid=%d) entered.\n", arg, gettid());
    printf("4 Sleeping\n");
    sleep(5);

    printf("4 broadcast cond1\n");
    pthread_cond_broadcast(&cond1);
    printf("Thread 4 done.\n");
    return 0;
}

int main(int argc, const char *argv[])
{
    pthread_t t[4];

    pthread_cond_init(&cond1, NULL);
    pthread_cond_init(&cond2, NULL);
    pthread_create( &t[0], NULL, thread1_func, (void *)1 );
    pthread_create( &t[1], NULL, thread2_func, (void *)2 );
    pthread_create( &t[2], NULL, thread3_func, (void *)3 );
    pthread_create( &t[3], NULL, thread4_func, (void *)4 );

    pthread_join(t[0], NULL);
    pthread_join(t[1], NULL);
    pthread_join(t[2], NULL);
    pthread_join(t[3], NULL);
    return 0;
}