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 #define QUEUE_SIZE 5 00003 Mutex mutex1; 00004 Mutex mutex2; 00005 ConditionVariable full(mutex1); 00006 ConditionVariable empty(mutex2); 00007 Thread producer; 00008 Thread consumer; 00009 00010 00011 typedef struct { 00012 uint8_t counter; /* A counter value */ 00013 } element_t; 00014 00015 00016 MemoryPool<element_t, QUEUE_SIZE> mpool; 00017 Queue<element_t, QUEUE_SIZE> queue; 00018 volatile int in_queue_elements = 0; 00019 00020 00021 00022 void producer_thread(void) { 00023 while (1) { 00024 mutex1.lock(); 00025 if (in_queue_elements == QUEUE_SIZE) { 00026 full.wait(); 00027 } 00028 element_t *element = mpool.alloc(); 00029 element->counter = in_queue_elements+1; 00030 queue.put(element); 00031 in_queue_elements++; 00032 printf("++There are %d elements in the queue\n", in_queue_elements); 00033 if (in_queue_elements == 1) { 00034 full.notify_all(); 00035 } 00036 mutex1.unlock(); 00037 if (rand() % 10 < 2) { 00038 wait(rand()%2); 00039 } 00040 } 00041 } 00042 00043 void consumer_thread(void) { 00044 while (1) { 00045 mutex1.lock(); 00046 if (in_queue_elements == 0) { 00047 full.wait(); 00048 } 00049 osEvent evt = queue.get(); 00050 if (evt.status == osEventMessage) { 00051 element_t *element = (element_t*)evt.value.p; 00052 printf("Got element: %u\n", element->counter); 00053 mpool.free(element); 00054 in_queue_elements--; 00055 } 00056 00057 printf("--There are %d elements in the queue\n", in_queue_elements); 00058 if (in_queue_elements == QUEUE_SIZE-1) { 00059 full.notify_all(); 00060 } 00061 mutex1.unlock(); 00062 if (rand() % 10 < 2) { 00063 wait(rand()%2); 00064 } 00065 } 00066 } 00067 00068 int main() { 00069 // Create a thread to execute the function led2_thread 00070 producer.start(producer_thread); 00071 consumer.start(consumer_thread); 00072 // Now led2_thread is executing concurrently with main at this point 00073 00074 }
Generated on Thu Jul 14 2022 15:26:33 by
1.7.2