我在尝试制作调用异步函数的同步函数时遇到了一些问题。(python 3.6.9,cocotb 1.4.0)
如以下示例代码所示。该read_cb
函数将调用read
函数(在FakeDriver
类中)。
运行后,我得到错误
yield self._fake_lock()
RuntimeError: Task got bad yield: <cocotb.decorators.RunningCoroutine object at 0x7f7fecdbfe10>
我想要的是
init FakerDriver
locking...
locking done
read...
addr: 0x01
unlocking...
unlocking done
read done
import cocotb
import asyncio
from cocotb.decorators import coroutine
from cocotb.triggers import Event
class FakeDriver():
def __init__(self):
print("init FakeDriver")
self.busy_event = Event("driver_busy")
self.busy = False
@coroutine
def read(self, addr):
print("read...")
yield self._fake_lock()
print("addr: ", addr)
self._fake_unlock()
print("read done")
@coroutine
def _fake_lock(self):
print("locking...")
if self.busy:
yield self.busy_event.wait()
self.busy_event.clear()
self.busy = True
print("locking done")
def _fake_unlock(self):
print("unlocking...")
self.busy = False
self.busy_event.set()
print("unlocking done")
def read_cb():
dri = FakeDriver()
loop = asyncio.get_event_loop()
task = loop.create_task(dri.read("0x01"))
ret = loop.run_until_complete(task)
loop.close()
if __name__ == "__main__":
read_cb()