summaryrefslogtreecommitdiff
path: root/regress/lib/libpthread/cond2/cond2.c
blob: 7fa17087699a7de2c8849b4b4d812c016fd65a05 (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
/*	$NetBSD: cond2.c,v 1.1 2003/01/30 18:53:46 thorpej Exp $	*/

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

void *threadfunc(void *arg);

pthread_mutex_t mutex;
pthread_cond_t cond;

int
main(int argc, char *argv[])
{
	int x,ret;
	pthread_t new;
	void *joinval;
	int sharedval;

	printf("1: condition variable test 2\n");

	pthread_mutex_init(&mutex, NULL);
	pthread_cond_init(&cond, NULL);

	x = 20;
	pthread_mutex_lock(&mutex);

	sharedval = 1;

	ret = pthread_create(&new, NULL, threadfunc, &sharedval);
	if (ret != 0)
		err(1, "pthread_create");

	printf("1: Before waiting.\n");
	do {
		sleep(2);
		pthread_cond_wait(&cond, &mutex);
		printf("1: After waiting, in loop.\n");
	} while (sharedval != 0);

	printf("1: After the loop.\n");

	pthread_mutex_unlock(&mutex);

	printf("1: After releasing the mutex.\n");
	ret = pthread_join(new, &joinval);
	if (ret != 0)
		err(1, "pthread_join");

	printf("1: Thread joined.\n");

	return 0;
}

void *
threadfunc(void *arg)
{
	int *share = (int *) arg;

	printf("2: Second thread.\n");

	printf("2: Locking mutex\n");
	pthread_mutex_lock(&mutex);
	printf("2: Got mutex.\n");
	printf("Shared value: %d. Changing to 0.\n", *share);
	*share = 0;
	
	/* Signal first, then unlock, for a different test than #1. */
	pthread_cond_signal(&cond);
	pthread_mutex_unlock(&mutex);

	return NULL;
}