remove sleepAsync for synchronization

This commit is contained in:
Dmitriy Ryajov 2020-02-12 09:39:32 -05:00
parent 53e163abf2
commit f4e9bc8bfb
1 changed files with 22 additions and 20 deletions

View File

@ -103,30 +103,32 @@ proc pushTo*(s: BufferStream, data: seq[byte]) {.async.} =
## is preserved. ## is preserved.
## ##
await s.lock.acquire() try:
var index = 0 await s.lock.acquire()
while true: var index = 0
while true:
# give readers a chance free up the buffer
# it it's full.
if s.readBuf.len >= s.maxSize:
await sleepAsync(1.millis)
# give readers a chance free up the buffer while index < data.len and s.readBuf.len < s.maxSize:
# it it's full. s.readBuf.addLast(data[index])
if s.readBuf.len >= s.maxSize: inc(index)
await sleepAsync(10.millis)
while index < data.len and s.readBuf.len < s.maxSize: # resolve the next queued read request
s.readBuf.addLast(data[index]) if s.readReqs.len > 0:
inc(index) s.readReqs.popFirst().complete()
# resolve the next queued read request if index >= data.len:
if s.readReqs.len > 0: return
s.readReqs.popFirst().complete()
if index >= data.len: # if we couldn't transfer all the data to the
break # internal buf wait on a read event
await s.dataReadEvent.wait()
# if we couldn't transfer all the data to the s.dataReadEvent.clear()
# internal buf wait on a read event finally:
await s.dataReadEvent.wait() s.lock.release()
s.lock.release()
method read*(s: BufferStream, n = -1): Future[seq[byte]] {.async.} = method read*(s: BufferStream, n = -1): Future[seq[byte]] {.async.} =
## Read all bytes (n <= 0) or exactly `n` bytes from buffer ## Read all bytes (n <= 0) or exactly `n` bytes from buffer