【发布时间】:2026-02-22 21:30:01
【问题描述】:
这是我现在面临的一个场景,我有一个中断(线程)UART,它正在从我从串行端口获得的值中读取环形缓冲区,并将值从串行端口写入环形缓冲区。 我有一个主循环,可以访问该环形缓冲区以从中读取值,同时编写 AT 命令,并将这些 AT 命令写入环形缓冲区。 我需要环形缓冲区是无锁的还是用信号量或互斥体包围共享数据?我没有让互斥锁或信号量工作的操作系统。 我已经阅读了很多关于该主题的内容,看来我需要一个无锁环形缓冲区。在 ARM 上,我会使用比较和交换指令。 ringbuffer 是作为数组实现的,所以我不会遇到 ABA 问题
缓冲区声明:
#define MAX_CHANNEL_COUNT 5
#define UART_BUFSIZE 512
char buffers[2][MAX_CHANNEL_COUNT][UART_BUFSIZE];
char* writeBuffers[MAX_CHANNEL_COUNT];
char* readBuffers[MAX_CHANNEL_COUNT];
volatile int readPos[MAX_CHANNEL_COUNT] = { 0 };
volatile int writePos[MAX_CHANNEL_COUNT] = { 0 };
here is the interrupt code
void USART_IRQHandler(char Channel, USART_TypeDef *USARTx)
{
volatile unsigned int IIR;
int c = 0;
IIR = USARTx->SR;
if (IIR & USART_FLAG_RXNE)
{ // read interrupt
USARTx->SR &= ~USART_FLAG_RXNE; // clear interrupt
c = USART_ReceiveData(USARTx);
writeBuffers[Channel][writePos[Channel]] = c;
writePos[Channel]++;
if(writePos[Channel]>=UART_BUFSIZE) writePos[Channel]=0;
}
if (IIR & USART_FLAG_TXE)
{
USARTx->SR &= ~USART_FLAG_TXE; // clear interrupt
}
}
code for initializing and swapping the buffers:
void initializeBuffers(void) {
int i = 0;
for (i = 0; i < MAX_CHANNEL_COUNT; ++i)
{
writeBuffers[i] = buffers[0][i];
readBuffers[i] = buffers[1][i];
}
}
void swapBuffers(int channel) {
int i;
char * buf = writeBuffers[channel];
__disable_irq();
writeBuffers[channel] = readBuffers[channel];
readBuffers[channel] = buf;
if ( readPos[channel] == UART_BUFSIZE)
readPos[channel] = 0;
for (i =0; i < UART_BUFSIZE; i++)
{
buf[i] = 0;
}
__enable_irq();
}
这里我使用此函数从特定通道和特定 UART 获取字符
int GetCharUART (char Channel)
{
int c = readBuffers[Channel][readPos[Channel]++];
if (c == 0 || readPos[Channel] == UART_BUFSIZE)
{
swapBuffers(Channel); // Make this clear your read buffer.
return EMPTY;
}
return c; // Note, your code that calls this should handle the case where c == 0
}
GetCharUart 的使用
PutStringUART(UART_GSM, "AT");
PutStringUART(UART_GSM, pCommand);
PutCharUART(UART_GSM, '\r');
count = 0;
timer_100ms = 0;
while (timer_100ms <= timeout)
{
zeichen = GetCharUART(UART_GSM);
}
【问题讨论】:
-
我觉得需要一些代码来说明一下对缓冲区的操作,同时还要更清楚地列出生产者和消费者。听起来 UART ISR 可以生产东西,而且主线程确实生产/消费,这似乎不平衡且令人困惑。或许您需要两个环形缓冲区,每个缓冲区在中断和主代码之间单向运行?
-
@unwind 我有一些代码。
-
我昨天给了你一个帖子的链接,该帖子解释了为什么需要信号量以及如何在裸机 MCU 上以最简单的方式实现它。发生了什么?这是链接,electronics.stackexchange.com/a/409570/6102,它解释了 volatile 的使用以及如何在同一答案中使用信号量。这是两个不相关的问题。
-
@Lundin 该帖子已被版主删除。
-
AhmedSaleh,提示:考虑使用包含 1 个
struct且有 5 个成员的数组,而不是 5 个数组对象。