Board logo

标题: 消息队列的设计与实现(2) [打印本页]

作者: yuyang911220    时间: 2015-6-28 17:08     标题: 消息队列的设计与实现(2)

写操作如上面的流程图介绍,写操作主要包括如下几步:- 获取锁;
/* lock the message queue */
pthread_mutex_lock (_msg_queue->lock);

/* check if the queue is full. */
if ((_msg_queue->write_pos + 1)% _msg_queue->size == _msg_queue->read_pos) {
    /* Message queue is full. */
    pthread_mutex_unlock (_msg_queue->lock);
    return;
}

/* write a data to write_pos. */
_msg_queue -> msg [write_pos] = *msg;
write_pos ++;

/* check if write_pos if overflow. */
if (_msg_queue->write_pos >= _msg_queue->size)
    _msg_queue->write_pos = 0;

/* release lock */
pthread_mutex_unlock (_msg_queue->lock);

sem_post (_msg_queue->wait);

读操作同理,读操作分如下几个步骤:
sem_wait (_msg_queue->wait);

/* lock the message queue */
pthread_mutex_lock (_msg_queue->lock);

/* check if queue is empty */
if (_msg_queue->read_pos != _msg_queue->write_pos) {
    msg = _msg_queue->msg + _msg_queue->read_pos;

/* read a data and check if read_pos is overflow */
    _msg_queue->read_pos ++;
    if (_msg_queue->read_pos >= _msg_queue->size)
        _msg_queue->read_pos = 0;

    return;
}

/* release lock*/
pthread_mutex_unlock (_msg_queue->lock);


问题




欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) Powered by Discuz! 7.0.0