BrianAssign3/msg_queue.c
/* Brain
* CSCI 4100 Assignment 3
* Source file for message queue implementation
*/
#include
#include "msg_queue.h"
/* Initialize the message queue */
void mq_init(struct msg_queue * mq)
{
/* YOUR CODE HERE */
mq->in = 0;
mq->out = 0;
pthread_mutex_init(&mq->lock,NULL);
pthread_cond_init(&mq->msg_added, NULL);
pthread_cond_init(&mq->msg_removed, NULL);
}
/* Send a message to a message queue */
void mq_send(struct msg_queue * mq, struct mq_msg * message)
{
/* YOUR CODE HERE */
//a. Acquire the queue lock.
pthread_mutex_lock(&mq->lock);
//b. While the queue is full, wait on the queue’s msg_removed condition variable.
while((mq->in)==QUEUE_SIZE)
{
pthread_cond_wait(&mq->msg_removed, &mq->lock);
}
//c. Copy the message from the mq_msg structure provided to the correct location in the queue.
mq->messages[mq->in].m_id = message->m_id;
//d. Increment the queue’s in member variable.
mq->in++;
//e. Signal the queue’s msg_added condition variable.
pthread_cond_signal(&mq->msg_added);
//f. Release the queue lock.
pthread_mutex_unlock(&mq->lock);
}
/* Receive a message from a message queue */
void mq_receive(struct msg_queue *mq, struct mq_msg * message)
{
/* YOUR CODE HERE */
//a. Acquire the queue lock.
pthread_mutex_lock(&mq->lock);
//b. While the queue is empty, wait on the queue’s msg_added condition variable
while((mq->in)==0)
{
pthread_cond_wait(&mq->msg_added, &mq->lock);
}
//c. Copy the message from the correct location in the queue to the mq_msg structure provided.
message->m_id=mq->messages[mq->out].m_id;
//d. Increment the queue’s out member variable.
mq->out++;
mq->in--;
//e. Signal the queue’s msg_removed condition variable.
pthread_cond_signal(&mq->msg_removed);
//f. Release the queue lock.
pthread_mutex_unlock(&mq->lock);
}
BrianAssign3/msg_queue.h
/* Brain
* CSCI 4100 Assignment 3
* Header file for message queue structures and functions
*/
#ifndef MSG_QUEUE_H
#define MSG_QUEUE_H
#include
#define QUEUE_SIZE 10
/* Structure for a message */
struct mq_msg {
int t_id; // sender thread id
...