RT-Thread设计与实现(七)消息队列

    科技2022-07-13  124

    #include <rtthread.h> #include <rtdevice.h> #include <board.h> #define THREAD_PRIORITY 9 #define THREAD_TIMESLICE 5 #define THREAD_STACK_SIZE 1024 static struct rt_messagequeue mq; static rt_uint8_t msg_pool[2048]; static rt_thread_t thread1 = RT_NULL; static rt_thread_t thread2 = RT_NULL; static void thread1_entry(void *parameter) { char buf; rt_uint8_t cnt=0; while(1) { if(rt_mq_recv(&mq,&buf,sizeof(buf),RT_WAITING_FOREVER)==RT_EOK) { rt_kprintf("thread1: recv msg from msg queue,the content:%c\n",buf); if(cnt == 19) { break; } } cnt++; rt_thread_mdelay(50); } rt_kprintf("thread1: detach mq \n"); rt_mq_detach(&mq); } static void thread2_entry(void *parameter) { int result; char buf='A'; rt_uint8_t cnt = 0; while(1) { if(cnt == 8) { result = rt_mq_urgent(&mq,&buf,1); if(result != RT_EOK) { rt_kprintf("rt_mq_urgent ERR\n"); } else { rt_kprintf("thread2:send urgent message - %c\n",buf); } } else if(cnt >=20) { rt_kprintf("message queue stop send,thread2 quit\n"); break; } else { result = rt_mq_send(&mq,&buf,1); if(result != RT_EOK) { rt_kprintf("rt_mq_send ERR"); } rt_kprintf("thread2: send message -%c\n",buf); } buf++; cnt++; rt_thread_mdelay(5); } } void msgq_init(void) { rt_err_t result; result = rt_mq_init(&mq,"mqt",&msg_pool,1,sizeof(msg_pool),RT_IPC_FLAG_FIFO); thread1=rt_thread_create( "thread1", thread1_entry, RT_NULL, THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE); thread2=rt_thread_create( "thread2", thread2_entry, RT_NULL, THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE); if(thread1!=RT_NULL) rt_thread_startup(thread1); if(thread2!=RT_NULL) rt_thread_startup(thread2); } int main(void) { msgq_init(); return RT_EOK; } MSH_CMD_EXPORT(msgq_init,msgq_init);
    Processed: 0.011, SQL: 8