Producer-Consumer
Embed:
(wiki syntax)
Show/hide line numbers
main.cpp
00001 #include "mbed.h" 00002 00003 typedef struct { 00004 int value; 00005 } message_t; 00006 Mutex mutex; 00007 const int queue_size = 10; 00008 ConditionVariable cond(mutex); 00009 MemoryPool<message_t, queue_size> mpool; 00010 Queue<message_t, queue_size> queue; 00011 Thread thread_producer; 00012 Thread thread_consumer; 00013 00014 int pointer = 0; 00015 00016 void producer () { 00017 while (true) { 00018 wait(rand()%3); 00019 mutex.lock(); 00020 int rand_value = rand(); 00021 message_t *message = mpool.alloc(); 00022 message->value = rand_value; 00023 queue.put(message); 00024 pointer++; 00025 printf("\nProducer value %d \n", message->value); 00026 while (pointer == queue_size){ 00027 printf("\nThe queue is full, wait a consumer\n"); 00028 cond.wait(); 00029 } 00030 cond.notify_all(); 00031 mutex.unlock(); 00032 } 00033 } 00034 00035 void consumer(){ 00036 while (true) { 00037 wait(rand()%5); 00038 mutex.lock(); 00039 while (pointer == 0){ 00040 printf("\nThe queue is empty, wait for a producer.\n"); 00041 cond.wait(); 00042 } 00043 osEvent evt = queue.get(); 00044 pointer--; 00045 if (evt.status == osEventMessage) { 00046 message_t *message = (message_t*)evt.value.p; 00047 printf("\nGot value %.d .\n" , message->value); 00048 mpool.free(message); 00049 } 00050 cond.notify_all(); 00051 mutex.unlock(); 00052 } 00053 00054 } 00055 00056 int main () { 00057 00058 thread_producer.start(&producer); 00059 thread_consumer.start(&consumer); 00060 00061 }
Generated on Sun Jul 17 2022 11:42:18 by
1.7.2