Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
main.cpp
00001 #include "mbed.h" 00002 00003 #define QUEUE_MAX_SIZE 32 00004 00005 typedef struct { 00006 int count; 00007 } message_t; 00008 00009 Queue<message_t, QUEUE_MAX_SIZE> queue; 00010 Mutex mutex; 00011 ConditionVariable cond(mutex); 00012 00013 int queue_size = 0; 00014 00015 00016 void consumer_thread() { 00017 while(true) { 00018 int wait_time = rand() % 5; 00019 printf("Consumer - Waiting %d seconds\n", wait_time); 00020 wait(wait_time); 00021 if (queue_size > 0) { 00022 printf("Consumer - Queue is not empty, getting message\n"); 00023 // Acquire the lock 00024 mutex.lock(); 00025 // Decrease the size of the queue 00026 queue_size--; 00027 // Get the message 00028 osEvent evt = queue.get(); 00029 // Extract the actual payload 00030 if (evt.status == osEventMessage) { 00031 message_t *message = (message_t *) evt.value.p; 00032 printf("Consumer - Got message with payload %d\n", message->count); 00033 } 00034 // Notify 00035 cond.notify_all(); 00036 00037 // Unlock the mutex 00038 mutex.unlock(); 00039 } else { 00040 printf("Consumer - Queue is empty! waiting for producer\n"); 00041 } 00042 } 00043 } 00044 00045 00046 int main() { 00047 Thread consumer; 00048 consumer.start(consumer_thread); 00049 00050 00051 while(1) { 00052 // Random wait time 00053 int wait_time = rand() % 5; 00054 printf("Producer - Waiting %d seconds\n", wait_time); 00055 wait(wait_time); 00056 if (queue_size < QUEUE_MAX_SIZE) { 00057 // Acquire the lock 00058 mutex.lock(); 00059 00060 // Increase the count 00061 queue_size++; 00062 00063 // create a new message 00064 message_t *message; 00065 message->count = queue_size; 00066 00067 // Add it to the queue 00068 queue.put(message); 00069 00070 printf("Producer - Added message to queue with payload %d\n", queue_size); 00071 00072 // Notify all 00073 cond.notify_all(); 00074 00075 // Unlock the mutex 00076 mutex.unlock(); 00077 } else { 00078 printf("Producer - Queue is full! waiting for consumer\n"); 00079 } 00080 } 00081 }
Generated on Sat Aug 13 2022 23:02:59 by
1.7.2