summaryrefslogtreecommitdiffstats
path: root/regress/lib/libpthread/malloc_duel/malloc_duel.c
blob: ad2b328bb92628d42fb0e523a7640a4edb5f07e5 (plain) (blame)
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
/* $OpenBSD: malloc_duel.c,v 1.3 2019/05/15 18:53:03 otto 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.
 */
static 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
 */
static void *
thread(void *arg)
{
	malloc_loop();
	return NULL;
}

#define NCHILDS	10
int
main(int argc, char **argv)
{
	pthread_t	child[NCHILDS];
	int i;

	for (i = 0; i < NCHILDS; i++)
		CHECKr(pthread_create(&child[i], NULL, thread, NULL));
	ASSERT(signal(SIGALRM, alarm_handler) != SIG_ERR);
	CHECKe(alarm(20));
	malloc_loop();
	for (i = 0; i < NCHILDS; i++)
		CHECKr(pthread_join(child[i], NULL));
	SUCCEED;
}