summaryrefslogtreecommitdiff
path: root/regress/lib/libpthread/malloc_duel/malloc_duel.c
blob: c7733f63b45c9cf23ee4d06a75c5882b4ae79870 (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
/* $OpenBSD: malloc_duel.c,v 1.1 2002/11/12 03:17:16 marc Exp $ */
/* PUBLIC DOMAIN Nov 2002 <marc@snafu.org> */

/*
 * Dueling malloc in different threads
 */

#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

#include "test.h"

volatile sig_atomic_t	done;

#define MALLOC_COUNT	1024

/*
 * sigalrm handler.  Initiate end-of-test
 */
static void
alarm_handler(int sig)
{
	done = 1;
}

/*
 * A function that does lots of mallocs, called by all threads.
 */
void
malloc_loop(void)
{
	int	i;
	int	**a;

	a = calloc(MALLOC_COUNT, sizeof(int*));
	ASSERT(a != NULL);
	while (!done) {
		for (i = 0; i < MALLOC_COUNT; i++) {
			a[i] = malloc(sizeof(int));
			ASSERT(a[i] != NULL);
		}
		for (i = 0; i < MALLOC_COUNT; i++) {
			free(a[i]);
		}
	}
}

/*
 * A thread that does a lot of mallocs
 */
void *
thread(void *arg)
{
	malloc_loop();
	return NULL;
}

int
main(int argc, char **argv)
{
	pthread_t	child;

	CHECKr(pthread_create(&child, NULL, thread, NULL));
	ASSERT(signal(SIGALRM, alarm_handler) != SIG_ERR);
	CHECKe(alarm(20));
	malloc_loop();
	CHECKr(pthread_join(child, NULL));
	SUCCEED;
}