Queue
Message Queuing is a common means of data exchange between threads in an operating system.
⊕ mxos-demos SDK를 참조한다.
1. Queue API
Queue API | Description |
mxos_rtos_init_queue | Initialize a message queue |
mxos_rtos_push_to_queue | Push a data object into a data object |
mxos_rtos_pop_from_queue | Take a data object from the message queue |
mxos_rtos_deinit_queue | Destroy a message queue |
mxos_rtos_is_queue_empty | Query if a message queue is empty |
mxos_rtos_is_queue_full | Query if a message queue is full |
2. os_queue.c code
#include "mxos.h"
#define os_queue_log(M, ...) custom_log("OS", M, ##__VA_ARGS__)
static mxos_queue_t os_queue = NULL;
typedef struct _msg
{
int value;
} msg_t;
void receiver_thread( mxos_thread_arg_t arg )
{
UNUSED_PARAMETER( arg );
OSStatus err;
msg_t received = { 0 };
while ( 1 )
{
/*Wait until queue has data*/
err = mxos_rtos_pop_from_queue( &os_queue, &received, mxos_WAIT_FOREVER );
require_noerr( err, exit );
os_queue_log( "Received data from queue:value = %d",received.value );
}
exit:
if ( err != kNoErr )
os_queue_log( "Receiver exit with err: %d", err );
mxos_rtos_delete_thread( NULL );
}
void sender_thread( mxos_thread_arg_t arg )
{
UNUSED_PARAMETER( arg );
OSStatus err = kNoErr;
msg_t my_message = { 0 };
while ( 1 )
{
my_message.value++;
mxos_rtos_push_to_queue( &os_queue, &my_message, mxos_WAIT_FOREVER );
require_noerr( err, exit );
os_queue_log( "send data to queue" );
mxos_thread_sleep( 1 );
}
exit:
if ( err != kNoErr )
os_queue_log( "Sender exit with err: %d", err );
mxos_rtos_delete_thread( NULL );
}
int application_start( void )
{
OSStatus err = kNoErr;
err = mxos_rtos_init_queue( &os_queue, "queue", sizeof(msg_t), 3 );
require_noerr( err, exit );
err = mxos_rtos_create_thread( NULL, mxos_APPLICATION_PRIORITY, "receiver", receiver_thread, 0x500, 0 );
require_noerr( err, exit );
err = mxos_rtos_create_thread( NULL, mxos_APPLICATION_PRIORITY, "sender", sender_thread, 0x500, 0 );
require_noerr( err, exit );
exit:
if ( err != kNoErr )
os_queue_log( "Thread exit with err: %d", err );
mxos_rtos_delete_thread( NULL );
return err;
}
♦ Achieve:
- The system creates two threads, one thread sends data to the message queue, one thread receives data from the message queue, and prints the data information.
- The data sent by the sending thread is incremented by 1 each time, and each thread sleeps for 1 second.
♦ Main function code annotations:
1) Invoke the mxos API to initialize a message queue: err = mxos_rtos_init_queue( &os_queue, “queue”, sizeof(msg_t), 3 );
2) Call the mxos API to write data to the message queue:
mxos_rtos_push_to_queue( &os_queue, &my_message, mxos_WAIT_FOREVER );
3) Call the mxos API to read data from the message queue:
err = mxos_rtos_pop_from_queue( &os_queue, &received, mxos_WAIT_FOREVER );
4)Call the mxos API to destroy an RTOS timer: mxos_deinit_timer( &timer_handle );
이상 끝 —