|
| 1 | +#include <rtt.h> |
| 2 | + |
| 3 | +// NOTES: "CONFIG_USING_SPISD" in "rtconfig.h" may be turned off to save memory |
| 4 | + |
| 5 | +#define THREAD_NUM 3 |
| 6 | +#define STACK_SIZE 256 |
| 7 | + |
| 8 | +struct rt_mutex lock; |
| 9 | + |
| 10 | +// user thread entry function |
| 11 | +void thread_entry(void* parameter) { |
| 12 | + unsigned int i = (unsigned int)parameter; |
| 13 | + |
| 14 | + rt_kprintf("Thread %d started\n", i); |
| 15 | + |
| 16 | + rt_kprintf("Thread %d tries to take mutex\n", i); |
| 17 | + rt_mutex_take(&lock, RT_WAITING_FOREVER); |
| 18 | + rt_kprintf("Thread %d took mutex\n", i); |
| 19 | + |
| 20 | + rt_kprintf("Thread %d goes to sleep\n", i); |
| 21 | + rt_thread_sleep(RT_TICK_PER_SECOND); |
| 22 | + rt_kprintf("Thread %d woken up\n", i); |
| 23 | + |
| 24 | + rt_mutex_release(&lock); |
| 25 | + rt_kprintf("Thread %d released mutex\n", i); |
| 26 | + |
| 27 | + rt_kprintf("Thread %d exits\n", i); |
| 28 | + rt_thread_yield(); |
| 29 | +} |
| 30 | + |
| 31 | +// RT-Thread function called by "RT_T.begin()" |
| 32 | +void rt_setup(void) { |
| 33 | + unsigned int i; |
| 34 | + char name[] = "thread_x"; |
| 35 | + rt_thread_t tid[THREAD_NUM]; |
| 36 | + |
| 37 | + // dynamically initialize threads |
| 38 | + for (i = 0; i < THREAD_NUM; i++) { |
| 39 | + name[7] = '1' + i; |
| 40 | + if (RT_NULL == (tid[i] = rt_thread_create( |
| 41 | + name, // [in] thread name |
| 42 | + thread_entry, // [in] thread entry function |
| 43 | + (void *)i, // [in] thread parameter (for entry function) |
| 44 | + STACK_SIZE, // [in] thread stack size |
| 45 | + 10, // [in] thread priority |
| 46 | + 20))) { // [in] thread ticks |
| 47 | + rt_kprintf("Failed to create thread %d!\n", i); |
| 48 | + return; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + // statically initialize mutex |
| 53 | + if (RT_EOK != rt_mutex_init(&lock, "lock", RT_IPC_FLAG_FIFO)) { |
| 54 | + rt_kprintf("Failed to initialize mutex!\n"); |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + // start threads |
| 59 | + for (i = 0; i < THREAD_NUM; i++) { |
| 60 | + rt_thread_startup(tid[i]); |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +void setup() { |
| 65 | + RT_T.begin(); |
| 66 | +} |
| 67 | + |
| 68 | +// this function will be called by "Arduino" thread |
| 69 | +void loop() { |
| 70 | + // may put some code here that will be run repeatedly |
| 71 | +} |
0 commit comments