Francesco Arrigo / Mbed 2 deprecated ProducerConsumer

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #define MAX_ELEMENTS 5
00003 
00004 Mutex mutex1;
00005 Mutex mutex2;
00006 ConditionVariable full(mutex1);
00007 ConditionVariable empty(mutex2);
00008 Thread producer;
00009 Thread consumer;
00010 
00011 
00012 typedef struct element_s{
00013     uint8_t counter;
00014 } element_t;
00015 
00016 
00017 MemoryPool<element_t, MAX_ELEMENTS> mpool;
00018 Queue<element_t, MAX_ELEMENTS> queue;
00019 volatile int current_elements = 0;
00020 
00021 
00022 
00023 void producer_thread(void) {
00024     while (1) {
00025       mutex1.lock();
00026       if (current_elements == MAX_ELEMENTS) {
00027         printf("The queue is full!\n");
00028         full.wait();    
00029       }
00030       element_t *element = mpool.alloc();
00031       element->counter = current_elements+1; 
00032       queue.put(element);
00033       current_elements++;
00034       printf("Adding element, now the queue is %d\n", current_elements);
00035       if (current_elements == 1) {
00036         full.notify_all();
00037       }
00038       mutex1.unlock();
00039       // randomly decide to keep producing or start consuming
00040       if (rand() % 10 < 2) {
00041             wait(rand()%2);
00042     }
00043     }
00044 }
00045 
00046 void consumer_thread(void) {
00047     while (1) {
00048         mutex1.lock();
00049         if (current_elements == 0) {
00050           printf("The queue is empty!\n");
00051           full.wait();    
00052         }
00053         osEvent evt = queue.get();
00054         if (evt.status == osEventMessage) {
00055           element_t *element = (element_t*)evt.value.p;
00056           mpool.free(element);
00057           current_elements--;
00058         }
00059         
00060         printf("Removing element, now the queue is %d\n", current_elements);
00061         if (current_elements == MAX_ELEMENTS-1) {
00062           full.notify_all();   
00063         }    
00064         mutex1.unlock();
00065         
00066         // randomly decide to keep consuming or start producing
00067         if (rand() % 10 < 2) {
00068             wait(rand()%2);
00069         }
00070     }
00071 }
00072 
00073 int main() {
00074     producer.start(producer_thread);
00075     consumer.start(consumer_thread);
00076 }