This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

C6657中断和主循环同时操作一个变量,怎么进行主循环的变量操作保护



1. 请教如下2个问题

  a.  在中断和主函数中同时操作1个变量,有没有什么方式保护主函数中的操作,例如其他CPU中的原子操作;

  b. 只是单独在这句话的操作前关闭中断,操作后开中断,还是异常,感觉没有起到保护作用;

2. 问题的具体描述

 a. 串口发送中断中每发送一个数据,则数据总数减一Uart0Tx.TxNum--

中断函数

if(Uart0Tx.TxNum>0)
{
while (!UART_Tx_Ready(0));
LocalUartRegs->RBR = (CSL_UART_THR_DATA_MASK & Uart0Tx.TxBuf[Uart0Tx.TxIndex]);
Uart0Tx.TxNum = Uart0Tx.TxNum -1;
Uart0Tx.TxIndex = (Uart0Tx.TxIndex + 1)%Uart0Tx.BufSize;

}

b. 而在main函数中缓存中写入一个数据,则数据总数Uart0Tx.TxNum加一

for(i = 0;i<DataLen+5;i++)
{
Uart0Tx.TxBuf[Uart0Tx.TxWriteIndex] = senddata[i];
Uart0Tx.TxWriteIndex = (Uart0Tx.TxWriteIndex+1)%Uart0Tx.BufSize;

Uart0Tx.TxNum = Uart0Tx.TxNum+1;

}

在调试中发现Uart0Tx.TxNum变量异常,有时候数据总数多1个,有时候数据总数少1个,

其他变量正常。

(1). 单独在Uart0Tx.TxNum变量操作前关闭串口中断,操作完后关闭串口发送中断,程序还是异常,如下所示:

for(i = 0;i<DataLen+5;i++)
{
Uart0Tx.TxBuf[Uart0Tx.TxWriteIndex] = senddata[i];
Uart0Tx.TxWriteIndex = (Uart0Tx.TxWriteIndex+1)%Uart0Tx.BufSize;

CpIntc0Regs->HINT_ENABLE_CLR_INDEX_REG= 44;   //关中断

Uart0Tx.TxNum = Uart0Tx.TxNum+1;

CpIntc0Regs->HINT_ENABLE_SET_INDEX_REG= 44;   //开中断

}

(2) 在整个代码操作前关闭串口中断,操作完后关闭串口发送中断,程序正常,如下所示:

CpIntc0Regs->HINT_ENABLE_CLR_INDEX_REG= 44;   //关中断

for(i = 0;i<DataLen+5;i++)
{
Uart0Tx.TxBuf[Uart0Tx.TxWriteIndex] = senddata[i];
Uart0Tx.TxWriteIndex = (Uart0Tx.TxWriteIndex+1)%Uart0Tx.BufSize;

Uart0Tx.TxNum = Uart0Tx.TxNum+1;

}

CpIntc0Regs->HINT_ENABLE_SET_INDEX_REG= 44;   //开中断