Skip to content

Commit

Permalink
refactor: remove pushing chanAddr on recv/send retry
Browse files Browse the repository at this point in the history
  • Loading branch information
shenyih0ng committed Apr 4, 2024
1 parent e99094f commit 7ab344c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 20 deletions.
23 changes: 11 additions & 12 deletions src/go-slang/goroutine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,26 +309,25 @@ const Interpreter: {
},

ChanRecvOp: (_inst, { C, S, H }) => {
const chanAddr = S.pop()
const chanAddr = S.peek()
const chan = H.resolve(chanAddr) as BufferedChannel

const chanValue = chan.recv()
if (chanValue !== null) { return S.push(H.alloc(chanValue)) } // prettier-ignore
// if the channel is empty, we retry the receive operation
if (chan.isBufferEmpty()) { return C.push(ChanRecv) } // prettier-ignore

// retry receiving from the channel
S.push(chanAddr)
C.push(ChanRecv)
S.pop()
S.push(H.alloc(chan.recv()))
},

ChanSendOp: (_inst, { C, S, H }) => {
const addrs = S.popN(2)
const [channel, value] = H.resolveM(addrs) as [BufferedChannel, any]
const chanAddr = S.peek()
const chan = H.resolve(chanAddr) as BufferedChannel

if (channel.send(value)) { return } // prettier-ignore
// if the channel is full, we retry the send operation
if (chan.isBufferFull()) { return C.push(ChanSend) } // prettier-ignore

// retry sending to the channel
S.pushR(...addrs)
C.push(ChanSend)
const [_, valueAddr] = S.popN(2)
chan.send(H.resolve(valueAddr))
},

BranchOp: ({ cons, alt }: BranchOp, { S, C, H }) =>
Expand Down
16 changes: 8 additions & 8 deletions src/go-slang/lib/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ export class BufferedChannel extends Channel {
return value
}

public isBufferFull(): boolean {
return this.bufSize === this.maxBufSize
}

public isBufferEmpty(): boolean {
return this.bufSize === 0
}

private get readIdx(): number {
return this.memory.getUint8(BufferedChannel.READ_IDX_OFFSET)
}
Expand All @@ -65,12 +73,4 @@ export class BufferedChannel extends Channel {
private set bufSize(newBufSize: number) {
this.memory.setUint8(BufferedChannel.BUF_SIZE_OFFSET, newBufSize)
}

private isBufferFull(): boolean {
return this.bufSize === this.maxBufSize
}

private isBufferEmpty(): boolean {
return this.bufSize === 0
}
}

0 comments on commit 7ab344c

Please sign in to comment.