用c实现一个阻塞的消息队列

该消息队列的实现,完全是符合posix标准。

实现了

1.读时,队列空,会阻塞

2.写时,队列满,会阻塞

为了保证线程安全,采用了互斥量,为了阻塞一定时间,采用了条件变量,二者一起用,实现了一个简单消息队列

simple_queue.c

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
#include<sys/time.h>
#include"simple_queue.h"

pthread_cond_t msg_cond = PTHREAD_COND_INITIALIZER;

simple_queue* create_simple_queue(const char* queue_name, int queue_length, int queue_type)
{
	simple_queue *this = NULL;
	
	if (NULL == queue_name || 0 == queue_length)
	{
		printf("[%s] param is error\n", __FUNCTION__);
		return NULL;
	}
	this = (simple_queue*)malloc(sizeof(simple_queue) + queue_length * sizeof(void*));
	if (NULL != this)
	{
		this->front = 0;
		this->rear = 0;
		this->length = queue_length;
		this->queue_type = queue_type;
		if (0 != pthread_mutex_init(&(this->data_mutex), NULL))
		{
				printf("[%s]pthread_mutex_init failed!\n", __FUNCTION__);
				free(this);
				this = NULL;
				return NULL;
		}
		strcpy(this->queue_name, queue_name);
	}
	else
	{
		printf("[%s]malloc is failed!\n", __FUNCTION__);
		return NULL;
	}
	
	return this;
}

/*
*/
queue_status is_full_queue(simple_queue* p_queue)
{
	queue_status ret = QUEUE_IS_NORMAL;
	
	do
	{
		if (NULL == p_queue)
		{
			printf("[%s] param is error\n", __FUNCTION__);
			ret = QUEUE_NO_EXIST;
			break;
		}
		if (p_queue->front == ((p_queue->rear + 1) % (p_queue->length)))
		{
			printf("[%s] queue is full\n", __FUNCTION__);
			ret = QUEUE_IS_FULL;
			break;
		}
	}while(0);
	
	return ret;
}

/*
*/
queue_status is_empty_queue(simple_queue* p_queue)
{
	queue_status ret = QUEUE_IS_NORMAL;
	
	do
	{
		if (NULL == p_queue)
		{
			printf("[%s] param is error\n", __FUNCTION__);
			ret = QUEUE_NO_EXIST;;
			break;
		}
		if (p_queue->front == p_queue->rear)
		{
			printf("[%s] queue is empty\n", __FUNCTION__);
			ret = QUEUE_IS_EMPTY;
			break;
		}
	}while(0);
	
	return ret;
}
/*
*/
cntl_queue_ret push_simple_queue(simple_queue* p_queue, void* data)
{
	int w_cursor = 0;
	
	if(NULL == p_queue || NULL == data)
	{
		printf("[%s] param is error\n", __FUNCTION__);
		return CNTL_QUEUE_PARAM_ERROR;
	}
	
	pthread_mutex_lock(&(p_queue->data_mutex));

	w_cursor = (p_queue->rear + 1)%p_queue->length;
	if (w_cursor == p_queue->front)
	{
		struct timeval now;
		struct timespec tsp;
		
		gettimeofday(&now, NULL);
		tsp.tv_sec = now.tv_sec + 5;
		tsp.tv_nsec = now.tv_usec * 1000;
		if (0 != pthread_cond_timedwait(&msg_cond, &(p_queue->data_mutex), &tsp))//队列满,等待消息被抛出,如果5秒内,没有消息被抛出,就返回
		{
			printf("[%s]: queue is full\n", __FUNCTION__);
			pthread_mutex_unlock(&(p_queue->data_mutex));
			return CNTL_QUEUE_TIMEOUT;
		}
		w_cursor = (p_queue->rear + 1)%p_queue->length;
	}
	p_queue->data[p_queue->rear] = data;
	p_queue->rear = w_cursor;

	pthread_mutex_unlock(&(p_queue->data_mutex));
	pthread_cond_signal(&msg_cond);
	//pthread_cond_broadcast(&msg_cond);
	
	return CNTL_QUEUE_SUCCESS;
}

/*
*/
cntl_queue_ret pop_simple_queue(simple_queue* p_queue, void** data)
{
	if(NULL == p_queue)
	{
		printf("[%s] param is error\n", __FUNCTION__);
		return CNTL_QUEUE_PARAM_ERROR;
	}

	pthread_mutex_lock(&(p_queue->data_mutex));
	
	if (p_queue->front == p_queue->rear)
	{
		struct timeval now;
		struct timespec tsp;
		
		gettimeofday(&now, NULL);
		tsp.tv_sec = now.tv_sec + 5;
		tsp.tv_nsec = now.tv_usec * 1000;
		if (0 != pthread_cond_timedwait(&msg_cond, &(p_queue->data_mutex), &tsp))//队列空,等待消息来临,如果5秒内,没有消息来,就返回
		{
			printf("[%s]: queue is empty\n", __FUNCTION__);
			pthread_mutex_unlock(&(p_queue->data_mutex));
			return CNTL_QUEUE_TIMEOUT;
		}
	}
	*data = p_queue->data[p_queue->front];
	p_queue->front = (p_queue->front + 1)%p_queue->length;
	
	pthread_mutex_unlock(&(p_queue->data_mutex));
	pthread_cond_signal(&msg_cond);
	//pthread_cond_broadcast(&msg_cond);
	
	return CNTL_QUEUE_SUCCESS;
}
cntl_queue_ret destroy_simple_queue(simple_queue* p_queue)
{
	cntl_queue_ret ret = CNTL_QUEUE_SUCCESS;
	
	if(NULL == p_queue)
	{
		printf("[%s] param is error\n", __FUNCTION__);
		ret = CNTL_QUEUE_PARAM_ERROR;
	}
	else
	{
		pthread_mutex_destroy(&(p_queue->data_mutex));
		pthread_cond_destroy(&msg_cond);
		while (p_queue->front != p_queue->rear)//删除队列中残留的消息
		{
			free(p_queue->data[p_queue->front]);
			p_queue->front = (p_queue->front + 1)%p_queue->length;
		}
		free(p_queue);
		p_queue = NULL;
	}
	
	return ret;
}
simple_queue.h

#ifndef _SIMPLE_QUEUE_H__
#define _SIMPLE_QUEUE_H__

#define MQ_NAME 						"test"
#define MQ_FLAG_BLOCK 					QUEUE_BLOCK
#define MQ_FLAG_NO_BLOCK 				QUEUE_NO_BLOCK
#define MQ_LENGTH_MAX 					10
#define MQ_SIZE_MAX 					512


typedef struct _simple_queue
{
	int front;
	int rear;
	int length;
	int queue_type;
	pthread_mutex_t data_mutex;
	char queue_name[15];
	void *data[0];
}simple_queue;

typedef struct _simple_queue_buf
{
	int msg_type;
	int msg_prio;
	char msg_buf[50];
	//char* msg_buf;
}queue_buf;

typedef enum _queue_type
{
	QUEUE_BLOCK = 0,
	QUEUE_NO_BLOCK,
}queue_type;

typedef enum _queue_status
{
	QUEUE_IS_NORMAL = 0,
	QUEUE_NO_EXIST,
	QUEUE_IS_FULL,
	QUEUE_IS_EMPTY,
	
}queue_status;

typedef enum _cntl_queue_ret
{
	CNTL_QUEUE_SUCCESS = 0,
	CNTL_QUEUE_FAIL,
	CNTL_QUEUE_TIMEOUT,
	CNTL_QUEUE_PARAM_ERROR,
}cntl_queue_ret;

simple_queue* create_simple_queue(const char* queue_name, int queue_length, int queue_type);
queue_status is_full_queue(simple_queue* p_queue);
queue_status is_empty_queue(simple_queue* p_queue);
cntl_queue_ret push_simple_queue(simple_queue* p_queue, void* data);
cntl_queue_ret pop_simple_queue(simple_queue* p_queue, void** data);
cntl_queue_ret destroy_simple_queue(simple_queue* p_queue);


#endif
main.c
#include<stdio.h>
#include<pthread.h>
//#include<errno.h>
#include<string.h>
#include<stdlib.h>
#include"simple_queue.h"

void* send_msg_thread(void* arg)
{
	#if 1
	queue_buf* send_buf = NULL;

	send_buf = (queue_buf*)malloc(sizeof(queue_buf));
	send_buf->msg_type = 9;
	send_buf->msg_prio = 6;

	strcpy(send_buf->msg_buf, "helloworld");
	printf("first1: rear =%d font =%d\n", ((simple_queue*)arg)->rear, ((simple_queue*)arg)->front);
	printf("send_buf = %p\n", send_buf);
    if (push_simple_queue((simple_queue*)arg, (void*)send_buf) < 0) 
	{ 
        printf("[%s]: push_simple_queue failed!\n", __FUNCTION__);  
        return NULL; 
    }
	
	printf("first2: rear =%d font =%d\n", ((simple_queue*)arg)->rear, ((simple_queue*)arg)->front);
	#if 1
	queue_buf* send_buf1 = NULL;

	send_buf1 = (queue_buf*)malloc(sizeof(queue_buf));
	send_buf1->msg_type = 9;
	send_buf1->msg_prio = 6;

	strcpy(send_buf1->msg_buf, "byebye");
	printf("first1: rear =%d font =%d\n", ((simple_queue*)arg)->rear, ((simple_queue*)arg)->front);
	printf("send_buf1 = %p\n", send_buf1);
    if (push_simple_queue((simple_queue*)arg, (void*)send_buf1) < 0) 
	{ 
        printf("[%s]: push_simple_queue\n", __FUNCTION__);  
        return NULL; 
    }
	printf("first2: rear =%d font =%d\n", ((simple_queue*)arg)->rear, ((simple_queue*)arg)->front);
	#endif
	#if 0
	queue_buf* recv_buf = NULL;
	 
	printf("recv_buf = %p\n", recv_buf);
	printf("seconde1 rear =%d font =%d\n", ((simple_queue*)arg)->rear, ((simple_queue*)arg)->front);	
    if (CNTL_QUEUE_SUCCESS != pop_simple_queue((simple_queue*)arg, (void**)&recv_buf)) 
	{  
        printf("[%s]: push_simple_queue failed!\n", __FUNCTION__); 
		return NULL;
    }
	printf("recv_buf = %p\n", recv_buf);
	printf("type = %d, prio = %d, recv_buf = %s\n", recv_buf->msg_type, recv_buf->msg_prio, recv_buf->msg_buf);
	printf("seconde2: rear =%d font =%d\n", ((simple_queue*)arg)->rear, ((simple_queue*)arg)->front);
	free(recv_buf);
	#endif
#endif
	return NULL;
}
void* recv_msg_thread(void* arg)
{
	#if 1
	queue_buf* recv_buf = NULL;
	//usleep(500);
	
	printf("recv_buf = %p\n", recv_buf);
	printf("seconde1 rear =%d font =%d\n", ((simple_queue*)arg)->rear, ((simple_queue*)arg)->front);
	
    if (CNTL_QUEUE_SUCCESS != pop_simple_queue((simple_queue*)arg, (void**)&recv_buf)) 
	{  
        printf("[%s]: pop_simple_queue failed!\n", __FUNCTION__); 
		return NULL;
    }
	printf("recv_buf = %p\n", recv_buf);
	printf("type = %d, prio = %d, recv_buf = %s\n", recv_buf->msg_type, recv_buf->msg_prio, recv_buf->msg_buf);
	printf("seconde2: rear =%d font =%d\n", ((simple_queue*)arg)->rear, ((simple_queue*)arg)->front);
	free(recv_buf);
	recv_buf = NULL;
	//queue_buf* recv_buf = NULL;
	//usleep(500);
#if 1	
	printf("recv_buf = %p\n", recv_buf);
	printf("seconde1 rear =%d font =%d\n", ((simple_queue*)arg)->rear, ((simple_queue*)arg)->front);
	
    if (CNTL_QUEUE_SUCCESS != pop_simple_queue((simple_queue*)arg, (void**)&recv_buf)) 
	{  
        printf("[%s]: pop_simple_queue failed!\n", __FUNCTION__); 
		return NULL;
    }
	printf("recv_buf = %p\n", recv_buf);
	printf("type = %d, prio = %d, recv_buf = %s\n", recv_buf->msg_type, recv_buf->msg_prio, recv_buf->msg_buf);
	printf("seconde2: rear =%d font =%d\n", ((simple_queue*)arg)->rear, ((simple_queue*)arg)->front);
	free(recv_buf);
	recv_buf = NULL;
	printf("recv_buf = %p\n", recv_buf);
#endif
	#if 0
	queue_buf* send_buf1 = NULL;

	send_buf1 = (queue_buf*)malloc(sizeof(queue_buf));
	send_buf1->msg_type = 9;
	send_buf1->msg_prio = 6;

	strcpy(send_buf1->msg_buf, "byebye");
	printf("first1: rear =%d font =%d\n", ((simple_queue*)arg)->rear, ((simple_queue*)arg)->front);
	printf("send_buf1 = %p\n", send_buf1);
    if (push_simple_queue((simple_queue*)arg, (void*)send_buf1) < 0) 
	{ 
        printf("[%s]: push_simple_queue\n", __FUNCTION__);  
        return NULL; 
    }
	printf("first2: rear =%d font =%d\n", ((simple_queue*)arg)->rear, ((simple_queue*)arg)->front);
	#endif
	#endif
	
	
	return NULL;
}
int main(int argc, char* argv[])
{
	int ret = 0;
	pthread_t send_thread_id = 0;
	pthread_t recv_thread_id = 0;
	simple_queue* msg_queue = NULL;
	#if 1
	msg_queue = create_simple_queue(MQ_NAME, MQ_LENGTH_MAX, MQ_FLAG_BLOCK);
	#else
	msg_queue = create_simple_queue(MQ_NAME, MQ_LENGTH_MAX, MQ_FLAG_NO_BLOCK);	
	#endif

	if (NULL == msg_queue)
	{
		printf("[%s]: create simple queue failed!\n", __FUNCTION__);
		return -1;
	}
	ret = pthread_create(&send_thread_id, NULL, send_msg_thread, (void*)msg_queue);
	if (0 != ret)
	{
		printf("[%s]: create send thread failed!\n", __FUNCTION__);
		return -1;
	}
	
	ret = pthread_create(&recv_thread_id, NULL, recv_msg_thread, (void*)msg_queue);
	if (0 != ret)
	{
		printf("[%s]: create recv thread failed!\n", __FUNCTION__);
		return -1;
	}
	printf("begin join\n");
	pthread_join(send_thread_id, NULL);
	pthread_join(recv_thread_id, NULL);
	printf("end join\n");
	ret = destroy_simple_queue(msg_queue);
	if (CNTL_QUEUE_SUCCESS != ret)
	{
		printf("[%s]: destroy simple queue failed!\n", __FUNCTION__);
		return -1;
	}
	
	return 0;
}

在linux下面编译

再运行

望大神指教

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
### 回答1: 反复读取一个队列消息的问题是一个常见的问题,特别是在消息队列系统中。首先,需要明确的是,消息队列是一种异步通信的方式,它将消息发送者和消息接收者解耦,提高了系统的可靠性和可伸缩性。 反复读取消息的过程可以通过轮询来实现。轮询是指在一个循环中不断地检查是否有新的消息到达。我们可以使用一个循环来不断地从队列中读取消息,并进行处理。当队列中没有新的消息时,我们可以选择休眠一段时间,然后再次进行轮询。这样可以减少不必要的资源消耗。 另一种方法是使用回调机制。当有新的消息到达时,可以注册一个回调函数来处理该消息。当消息到达时,系统会自动调用注册的回调函数进行处理。这样可以避免不断地轮询队列,提高系统的响应速度。 在处理消息时,我们需要注意一些问题。首先,如果消息处理失败,我们需要考虑如何处理这种情况。可以选择将消息重新放回队列中,等待下次处理,或者将消息转发到一个专门的错误队列中,由其他处理程序来处理。其次,对于并发访问队列的问题,我们需要考虑采用锁或者其他的同步机制来确保消息的处理是线程安全的。 总的来说,反复读取队列消息的问题是一个常见且重要的问题。通过合适的轮询或回调机制,结合适当的错误处理和同步机制,我们可以有效地处理队列中的消息。这些方法可以提高系统的可靠性、可伸缩性和响应速度。 ### 回答2: 反复读取队列消息是一个常见的问题,通常我们会使用循环来解决这个问题。 首先,我们需要确保连接到队列并且能够读取消息。这通常需要使用适当的库和函数。 然后,我们可以使用循环来反复读取队列中的消息。具体的步骤如下: 1. 初始化一个循环,确保程序能够一直运行下去。 2. 在每次循环开始时,调用相关的函数从队列中读取一条消息。 3. 检查读取的消息是否为空。如果为空,说明队列中没有消息,可以选择等待一段时间后再进行下一次循环,或者立即结束程序。 4. 如果读取到了消息,可以对该消息进行处理,如打印出来、存储到数据库中等等。 5. 在循环末尾,可以选择进行一些清理工作,如关闭连接等。 需要注意的是,循环的具体实现可能会根据使用的队列库和函数而略有不同。有些库可能提供了自动反复读取队列消息的方法,我们只需要简单地调用这个方法即可。 总而言之,反复读取一个队列消息的问题可以通过使用循环来解决,确保程序能够持续读取消息,并对消息进行处理。 ### 回答3: 反复读取一个队列消息问题c是指在程序中需要循环读取消息队列中的消息,并进行相应的处理。在解决这个问题时,我们可以使用以下步骤: 1. 创建一个消息队列,并定义消息格式:首先,我们需要创建一个消息队列,可以使用现有的消息队列库或者自己实现一个消息队列。同时,我们还需要定义消息的格式,包括消息的类型和内容。 2. 循环读取消息队列:在一个循环中,我们将不断地读取队列中的消息。可以使用一个无限循环,直到程序终止为止。 3. 处理收到的消息:当读取到消息后,我们需要根据消息的类型进行相应的处理。可以通过使用条件语句或者开关语句来判断消息的类型,并执行不同的处理逻辑。 4. 等待新消息的到来:如果当前队列为空,我们可以选择应用程序阻塞等待新的消息到来,或者使用定时器来定期检查是否有新的消息。 5. 释放资源:当程序终止或者不再需要读取消息队列时,需要手动释放所占用的资源,如关闭消息队列。 在处理这个问题时,需要考虑以下几个方面:首先是读取消息的频率和处理速度,如果消息队列中的消息过多,可能会造成消息处理速度跟不上消息到达的速度,从而导致消息堆积。其次是消息的持久化,即使程序终止,也要保证消息的不丢失。最后,还需要考虑程序的异常处理和错误处理,以及如何保证消息的顺序性。通过合理设计和实现,可以解决这个问题,并提高程序的性能和稳定性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值