> For the complete documentation index, see [llms.txt](https://book.bsdcn.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://book.bsdcn.org/man/man9/buf_ring.9.md).

# buf\_ring.9

`buf_ring` — 多生产者、{单, 多}消费者无锁环形缓冲区

## 名称

`buf_ring`, `buf_ring_alloc`, `buf_ring_free`, `buf_ring_enqueue`, `buf_ring_dequeue_mc`, `buf_ring_dequeue_sc`, `buf_ring_count`, `buf_ring_empty`, `buf_ring_full`, `buf_ring_peek`

## 概要

```c
#include <sys/param.h>
#include <sys/buf_ring.h>

struct buf_ring *
buf_ring_alloc(int count, struct malloc_type *type, int flags,
    struct mtx *sc_lock)

void
buf_ring_free(struct buf_ring *br, struct malloc_type *type)

int
buf_ring_enqueue(struct buf_ring *br, void *buf)

void *
buf_ring_dequeue_mc(struct buf_ring *br)

void *
buf_ring_dequeue_sc(struct buf_ring *br)

int
buf_ring_count(struct buf_ring *br)

int
buf_ring_empty(struct buf_ring *br)

int
buf_ring_full(struct buf_ring *br)

void *
buf_ring_peek(struct buf_ring *br)
```

## 描述

buf\_ring 函数提供无锁多生产者和无锁多消费者以及单消费者环形缓冲区。

`buf_ring_alloc` 函数用于分配具有 `count` 个槽位的 buf\_ring 环形缓冲区，使用 malloc\_type `type` 和内存标志 `flags`。单消费者接口由 `sc_lock` 保护。

`buf_ring_free` 函数用于释放 buf\_ring。用户负责释放任何已入队的项。

`buf_ring_enqueue` 函数用于将缓冲区入队到 buf\_ring。

`buf_ring_dequeue_mc` 函数是从 buf\_ring 出队元素的多消费者安全方式。

`buf_ring_dequeue_sc` 函数是出队元素的单消费者接口，要求用户使用锁串行化访问。

`buf_ring_count` 函数返回 buf\_ring 中的元素数量。

`buf_ring_empty` 函数在 buf\_ring 为空时返回 `TRUE`，否则返回 `FALSE`。

`buf_ring_full` 函数在不能再入队更多项时返回 `TRUE`，否则返回 `FALSE`。

`buf_ring_peek` 函数在 buf\_ring 不为空时返回指向 buf\_ring 中最后一个元素的指针，否则返回 `NULL`。

## 返回值

`buf_ring_enqueue` 函数在 buf\_ring 中没有可用槽位时返回 `ENOBUFS`。

## 历史

这些函数引入于 FreeBSD 8.0。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://book.bsdcn.org/man/man9/buf_ring.9.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
