1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 10:08:15 -05:00

add a lock to protect reader/writer from panic

This commit is contained in:
v2ray 2016-05-20 13:56:19 +02:00
parent 3ded18a75b
commit f5f13d801f
2 changed files with 30 additions and 0 deletions

View File

@ -2,11 +2,13 @@ package io
import ( import (
"io" "io"
"sync"
"github.com/v2ray/v2ray-core/common/alloc" "github.com/v2ray/v2ray-core/common/alloc"
) )
type BufferedReader struct { type BufferedReader struct {
sync.Mutex
reader io.Reader reader io.Reader
buffer *alloc.Buffer buffer *alloc.Buffer
cached bool cached bool
@ -21,6 +23,9 @@ func NewBufferedReader(rawReader io.Reader) *BufferedReader {
} }
func (this *BufferedReader) Release() { func (this *BufferedReader) Release() {
this.Lock()
defer this.Unlock()
this.buffer.Release() this.buffer.Release()
this.buffer = nil this.buffer = nil
this.reader = nil this.reader = nil
@ -35,6 +40,13 @@ func (this *BufferedReader) SetCached(cached bool) {
} }
func (this *BufferedReader) Read(b []byte) (int, error) { func (this *BufferedReader) Read(b []byte) (int, error) {
this.Lock()
defer this.Unlock()
if this.reader == nil {
return 0, io.EOF
}
if !this.cached { if !this.cached {
if !this.buffer.IsEmpty() { if !this.buffer.IsEmpty() {
return this.buffer.Read(b) return this.buffer.Read(b)

View File

@ -2,11 +2,13 @@ package io
import ( import (
"io" "io"
"sync"
"github.com/v2ray/v2ray-core/common/alloc" "github.com/v2ray/v2ray-core/common/alloc"
) )
type BufferedWriter struct { type BufferedWriter struct {
sync.Mutex
writer io.Writer writer io.Writer
buffer *alloc.Buffer buffer *alloc.Buffer
cached bool cached bool
@ -21,6 +23,13 @@ func NewBufferedWriter(rawWriter io.Writer) *BufferedWriter {
} }
func (this *BufferedWriter) Write(b []byte) (int, error) { func (this *BufferedWriter) Write(b []byte) (int, error) {
this.Lock()
defer this.Unlock()
if this.writer == nil {
return 0, io.EOF
}
if !this.cached { if !this.cached {
return this.writer.Write(b) return this.writer.Write(b)
} }
@ -35,6 +44,12 @@ func (this *BufferedWriter) Write(b []byte) (int, error) {
} }
func (this *BufferedWriter) Flush() error { func (this *BufferedWriter) Flush() error {
this.Lock()
defer this.Unlock()
if this.writer == nil {
return io.EOF
}
defer this.buffer.Clear() defer this.buffer.Clear()
for !this.buffer.IsEmpty() { for !this.buffer.IsEmpty() {
nBytes, err := this.writer.Write(this.buffer.Value) nBytes, err := this.writer.Write(this.buffer.Value)
@ -58,6 +73,9 @@ func (this *BufferedWriter) SetCached(cached bool) {
} }
func (this *BufferedWriter) Release() { func (this *BufferedWriter) Release() {
this.Lock()
defer this.Unlock()
this.Flush() this.Flush()
this.buffer.Release() this.buffer.Release()
this.buffer = nil this.buffer = nil