]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/tests/rtos/mbed/mutex/main.cpp
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / tests / rtos / mbed / mutex / main.cpp
1 #include "mbed.h"
2 #include "test_env.h"
3 #include "rtos.h"
4
5 #define THREAD_DELAY     50
6 #define SIGNALS_TO_EMIT  100
7
8 /*
9  * The stack size is defined in cmsis_os.h mainly dependent on the underlying toolchain and
10  * the C standard library. For GCC, ARM_STD and IAR it is defined with a size of 2048 bytes
11  * and for ARM_MICRO 512. Because of reduce RAM size some targets need a reduced stacksize.
12  */
13 #if defined(TARGET_STM32L053R8) || defined(TARGET_STM32L053C8)
14     #define STACK_SIZE DEFAULT_STACK_SIZE/4
15 #else
16     #define STACK_SIZE DEFAULT_STACK_SIZE
17 #endif
18
19 void print_char(char c = '*') {
20     printf("%c", c);
21     fflush(stdout);
22 }
23
24 Mutex stdio_mutex;
25 DigitalOut led(LED1);
26
27 volatile int change_counter = 0;
28 volatile bool changing_counter = false;
29 volatile bool mutex_defect = false;
30
31 bool manipulate_protected_zone(const int thread_delay) {
32     bool result = true;
33
34     stdio_mutex.lock(); // LOCK
35     if (changing_counter == true) {
36         // 'e' stands for error. If changing_counter is true access is not exclusively
37         print_char('e');
38         result = false;
39         mutex_defect = true;
40     }
41     changing_counter = true;
42
43     // Some action on protected
44     led = !led;
45     change_counter++;
46     print_char('.');
47     Thread::wait(thread_delay);
48
49     changing_counter = false;
50     stdio_mutex.unlock();   // UNLOCK
51     return result;
52 }
53
54 void test_thread(void const *args) {
55     const int thread_delay = int(args);
56     while (true) {
57         manipulate_protected_zone(thread_delay);
58     }
59 }
60
61 int main() {
62     MBED_HOSTTEST_TIMEOUT(20);
63     MBED_HOSTTEST_SELECT(default);
64     MBED_HOSTTEST_DESCRIPTION(Mutex resource lock);
65     MBED_HOSTTEST_START("RTOS_2");
66
67     const int t1_delay = THREAD_DELAY * 1;
68     const int t2_delay = THREAD_DELAY * 2;
69     const int t3_delay = THREAD_DELAY * 3;
70     Thread t2(test_thread, (void *)t2_delay, osPriorityNormal, STACK_SIZE);
71     Thread t3(test_thread, (void *)t3_delay, osPriorityNormal, STACK_SIZE);
72
73     while (true) {
74         // Thread 1 action
75         Thread::wait(t1_delay);
76         manipulate_protected_zone(t1_delay);
77         if (change_counter >= SIGNALS_TO_EMIT or mutex_defect == true) {
78             t2.terminate();
79             t3.terminate();
80             break;
81         }
82     }
83
84     fflush(stdout);
85     MBED_HOSTTEST_RESULT(!mutex_defect);
86     return 0;
87 }