You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我用Python实现的门控SR锁存器无法正常写入数据?

问题根因

你要实现的是D型电平锁存器,你设计的组合逻辑本身没有问题,错误出在你处理环路递归的逻辑上:你当前的自连接兼容逻辑只覆盖了「单个门自己接自己」的场景,但是SR锁存是「两个门互相连接形成环路」,这种场景下你的逻辑会触发无限递归,被捕获后锁存器的输出会被强制设为初始默认值,永远不会更新。

修复方案

步骤1:给Component类新增更新状态标志位

修改Component的__init__方法,新增is_updating属性用来标记当前门是否正在计算输出,避免循环递归:

def __init__(self, output, receiving_from_a = None, receiving_from_b = None, this_type = "Component"):
    self.output = output
    self.receiving_from_a = receiving_from_a
    self.receiving_from_b = receiving_from_b
    self.this_type = this_type
    # 新增:标记当前门是否正在更新输出,避免环路递归
    self.is_updating = False

步骤2:修改所有门的set_output逻辑,用标志位处理环路

删除你原本写的自连接判断逻辑,用is_updating标记拦截环路递归:

Not门修改

def set_output(self):
    if self.is_updating:
        return
    self.is_updating = True
    try:
        self.output = not (self.get_input())
    finally:
        self.is_updating = False

Or门修改

def set_output(self):
    if self.is_updating:
        return
    self.is_updating = True
    try:
        self.prev_out = self.output
        # 不需要再判断自连接,标志位已经处理了环路问题
        self.output = (self.get_input_a() or self.get_input_b())
    except RecursionError:
        self.output = self.prev_out
    finally:
        self.is_updating = False

And门修改

def set_output(self):
    if self.is_updating:
        return
    self.is_updating = True
    try:
        self.prev_out = self.output
        # 不需要再判断自连接
        self.output = (self.get_input_a() and self.get_input_b())
    except RecursionError:
        self.output = self.prev_out
    finally:
        self.is_updating = False

步骤3:测试验证

修改你的测试代码,添加状态打印和信号翻转逻辑验证功能:

data = Signal(True)
enable = Signal(False)

and1 = And(data, enable)
not_data = Not(data)
and2 = And(not_data, enable)
not_and2 = Not(and2)
bit = Latch(and1, not_and2)

print("初始状态 enable=False,data=True,bit输出:", bit.get_output())
enable.flip() # 开启写使能
print("开启写使能后,bit输出:", bit.get_output())
data.flip() # 数据改为False
print("data改为False,bit输出:", bit.get_output())
enable.flip() # 关闭写使能
data.flip() # 修改数据为True
print("关闭写使能后修改data,bit输出:", bit.get_output())

运行后输出应该符合锁存逻辑:

初始状态 enable=False,data=True,bit输出: False
开启写使能后,bit输出: True
data改为False,bit输出: False
关闭写使能后修改data,bit输出: False

内容的提问来源于stack exchange,提问作者Zachary F

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:30:05