我有一个多线程C程序(如下所示),多个编写器将元素添加到共享环形缓冲区,单个读取器从缓冲区读取元素。主要问题是缓冲区溢出!当元素数量超过缓冲区大小时,是否可以避免缓冲区溢出?
作家代码:
pthread_mutex_lock(&buffer_ptr->mutex);
if((buffer_ptr->tail + 1) % BUFFER_SIZE == buffer_ptr->head)
pthread_cond_wait( &buffer_ptr->cond_write, &buffer_ptr->mutex );
pthread_mutex_unlock(&buffer_ptr->mutex);
pthread_mutex_lock(&buffer_ptr->mutex);
if ((buffer_ptr->tail + 1) % BUFFER_SIZE != buffer_ptr->head)
{
memmove(buffer_ptr->chunk[buffer_ptr->tail], chunk, chunk_size); //Write chunk into buffer
buffer_ptr->chunk[buffer_ptr->tail][chunk_size] = '\0';
buffer_ptr->chunk_size[buffer_ptr->tail] = chunk_size; //Write chunk size into buffer
buffer_ptr->tail = (buffer_ptr->tail + 1) % BUFFER_SIZE;
}
pthread_cond_signal(&buffer_ptr->cond_write);
pthread_mutex_unlock(&buffer_ptr->mutex);
读者代码:
while (TRUE)
{
if (buffer_ptr->tail != buffer_ptr->head)
{
readchunk = TRUE;
chunksize = buffer_ptr->chunk_size[buffer_ptr->head]; //Read chunk size from buffer
memmove(chunk, buffer_ptr->chunk[buffer_ptr->head], chunksize); //Read chunk from buffer
chunk[chunksize] = '\0';
buffer_ptr->head = (buffer_ptr->head + 1) % BUFFER_SIZE;
}
}