偶然逛到別人的網站找到的
该实现中创建了两个队列,一个empty队列,用于存放预分配的缓冲区,也就是一个缓存池,另外一个是full队列。实际使用中,写者从empty队列中获取一个队列项,并将数据写入该队列项指定的地址,然后将该队列项放入full队列。读者从full队列中获得一个队列项,然后对这个队列项进行处理,处理完后将这个队列项重新放入empty队列中。
#include <osa_buf.h>
#include <string.h>
int OSA_bufDelete(OSA_BufHndl *hndl)
{
int status = OSA_SOK;
if(hndl == NULL)
return OSA_EFAIL;
status = OSA_queDelete(&hndl->emptyQue);
status |= OSA_queDelete(&hndl->fullQue);
return status;
}
int OSA_bufCreate(OSA_BufHndl *hndl, OSA_BufCreate *bufInit)
{
int status = OSA_SOK;
int i;
if(hndl == NULL || bufInit == NULL)
return OSA_EFAIL;
if(bufInit->numBuf > OSA_BUF_NUM_MAX)
return OSA_EFAIL;
memset(hndl, 0, sizeof(OSA_BufHndl));
status = OSA_queCreate(&hndl->emptyQue, bufInit->numBuf);
if(status != OSA_SOK) {
OSA_ERROR("OSA_bufCreate() = %d \r\n", status);
return status;
}
status = OSA_queCreate(&hndl->fullQue, bufInit->numBuf);
if(status != OSA_SOK) {
OSA_queDelete(&hndl->emptyQue);
OSA_ERROR("OSA_bufCreate() = %d \r\n", status);
return status;
}
hndl->numBuf = bufInit->numBuf;
for(i = 0; i < hndl->numBuf; i++) {
hndl->bufInfo[i].size = 0;
hndl->bufInfo[i].flags = 0;
hndl->bufInfo[i].timestamp = 0;
hndl->bufInfo[i].physAddr = bufInit->bufPhysAddr[i];
hndl->bufInfo[i].virtAddr = bufInit->bufVirtAddr[i];
OSA_quePut(&hndl->emptyQue, i, OSA_TIMEOUT_FOREVER);
}
return status;
}
int OSA_bufSwitchFull(OSA_BufHndl *hndl, int *bufId)
{
int status;
int newBufId;
status = OSA_bufGetEmpty(hndl, &newBufId, OSA_TIMEOUT_NONE);
if(status == OSA_SOK) {
if(*bufId != OSA_BUF_ID_INVALID)
OSA_bufPutFull(hndl, *bufId);
*bufId = newBufId;
}
return status;
}
int OSA_bufSwitchEmpty(OSA_BufHndl *hndl, int *bufId)
{
int status;
int newBufId;
status = OSA_bufGetFull(hndl, &newBufId, OSA_TIMEOUT_NONE);
if(status == OSA_SOK) {
if(*bufId != OSA_BUF_ID_INVALID)
OSA_bufPutEmpty(hndl, *bufId);
*bufId = newBufId;
}
return status;
}