a

main.cpp

Committer:
lucaspennati
Date:
2018-11-30
Revision:
1:cc715a7c24a5
Parent:
0:6ab5b8697bfb

File content as of revision 1:cc715a7c24a5:

#include "mbed.h"

#define QUEUE_MAX_SIZE 32

typedef struct {
    int count;
} message_t;

Queue<message_t, QUEUE_MAX_SIZE> queue;
Mutex mutex;
ConditionVariable cond(mutex);

int queue_size = 0;


void consumer_thread() {
    while(true) {
        int wait_time = rand() % 5;
        printf("Consumer - Waiting %d seconds\n", wait_time);
        wait(wait_time);
        if (queue_size > 0) {
            printf("Consumer - Queue is not empty, getting message\n");
            // Acquire the lock
            mutex.lock();
            // Decrease the size of the queue
            queue_size--;
            // Get the message
            osEvent evt = queue.get();
            // Extract the actual payload
            if (evt.status == osEventMessage) {
                message_t *message = (message_t *) evt.value.p;
                printf("Consumer - Got message with payload %d\n", message->count);
            }
            // Notify
            cond.notify_all();
            
            // Unlock the mutex
            mutex.unlock();
        } else {
            printf("Consumer - Queue is empty! waiting for producer\n");
        }
    }
}


int main() {
    Thread consumer;
    consumer.start(consumer_thread);
    
        
    while(1) {
        // Random wait time
        int wait_time = rand() % 5;
        printf("Producer - Waiting %d seconds\n", wait_time);
        wait(wait_time);
        if (queue_size < QUEUE_MAX_SIZE) {
            // Acquire the lock
            mutex.lock();
            
            // Increase the count
            queue_size++;
            
            // create a new message
            message_t *message;
            message->count = queue_size;
            
            // Add it to the queue
            queue.put(message);
            
            printf("Producer - Added message to queue with payload %d\n", queue_size);
            
            // Notify all 
            cond.notify_all();
            
            // Unlock the mutex
            mutex.unlock();
        } else {
            printf("Producer - Queue is full! waiting for consumer\n");
        }
    }
}