Skip to content

Commit 13c0685

Browse files
committed
Add a test for thread-safe malloc
Add a test to repeatedly malloc and free from different threads to test if these functions are thread safe.
1 parent 4b50628 commit 13c0685

File tree

1 file changed

+68
-0
lines changed
  • TESTS/mbedmicro-rtos-mbed/malloc

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#include "mbed.h"
2+
#include "test_env.h"
3+
#include "rtos.h"
4+
5+
#if defined(MBED_RTOS_SINGLE_THREAD)
6+
#error [NOT_SUPPORTED] test not supported
7+
#endif
8+
9+
#define NUM_THREADS 5
10+
#define THREAD_STACK_SIZE 256
11+
12+
DigitalOut led1(LED1);
13+
volatile bool should_exit = false;
14+
volatile bool allocation_failure = false;
15+
16+
void task_using_malloc(void)
17+
{
18+
void* data;
19+
while (1) {
20+
// Repeatedly allocate and free memory
21+
data = malloc(100);
22+
if (data != NULL) {
23+
memset(data, 0, 100);
24+
} else {
25+
allocation_failure = true;
26+
}
27+
free(data);
28+
29+
if (should_exit) {
30+
return;
31+
}
32+
}
33+
}
34+
35+
int main()
36+
{
37+
Thread *thread_list[NUM_THREADS];
38+
int test_time = 15;
39+
GREENTEA_SETUP(20, "default_auto");
40+
41+
// Allocate threads for the test
42+
for (int i = 0; i < NUM_THREADS; i++) {
43+
thread_list[i] = new Thread(osPriorityNormal, THREAD_STACK_SIZE);
44+
if (NULL == thread_list[i]) {
45+
allocation_failure = true;
46+
}
47+
thread_list[i]->start(task_using_malloc);
48+
}
49+
50+
// Give the test time to run
51+
while (test_time) {
52+
led1 = !led1;
53+
Thread::wait(1000);
54+
test_time--;
55+
}
56+
57+
// Join and delete all threads
58+
should_exit = 1;
59+
for (int i = 0; i < NUM_THREADS; i++) {
60+
if (NULL == thread_list[i]) {
61+
continue;
62+
}
63+
thread_list[i]->join();
64+
delete thread_list[i];
65+
}
66+
67+
GREENTEA_TESTSUITE_RESULT(!allocation_failure);
68+
}

0 commit comments

Comments
 (0)