THRIFT-4237 Fix data races in Go TServerSocket
Client: Go
Patch: Zachary Wasserman <zachwass2000@gmail.com>

This closes #1300
diff --git a/lib/go/Makefile.am b/lib/go/Makefile.am
index ff946ea..b26a890 100644
--- a/lib/go/Makefile.am
+++ b/lib/go/Makefile.am
@@ -31,7 +31,7 @@
 	@echo '##############################################################'
 
 check-local:
-	$(GO) test ./thrift
+	$(GO) test -race ./thrift
 
 all-local:
 	$(GO) build ./thrift
diff --git a/lib/go/thrift/server_socket.go b/lib/go/thrift/server_socket.go
index 5a88b80..68c9a02 100644
--- a/lib/go/thrift/server_socket.go
+++ b/lib/go/thrift/server_socket.go
@@ -53,6 +53,8 @@
 }
 
 func (p *TServerSocket) Listen() error {
+	p.mu.Lock()
+	defer p.mu.Unlock()
 	if p.IsListening() {
 		return nil
 	}
@@ -66,10 +68,9 @@
 
 func (p *TServerSocket) Accept() (TTransport, error) {
 	p.mu.RLock()
-	interrupted := p.interrupted
-	p.mu.RUnlock()
+	defer p.mu.RUnlock()
 
-	if interrupted {
+	if p.interrupted {
 		return nil, errTransportInterrupted
 	}
 	if p.listener == nil {
@@ -89,6 +90,8 @@
 
 // Connects the socket, creating a new socket object if necessary.
 func (p *TServerSocket) Open() error {
+	p.mu.Lock()
+	defer p.mu.Unlock()
 	if p.IsListening() {
 		return NewTTransportException(ALREADY_OPEN, "Server socket already open")
 	}
@@ -119,9 +122,9 @@
 
 func (p *TServerSocket) Interrupt() error {
 	p.mu.Lock()
+	defer p.mu.Unlock()
 	p.interrupted = true
 	p.Close()
-	p.mu.Unlock()
 
 	return nil
 }
diff --git a/lib/go/thrift/server_socket_test.go b/lib/go/thrift/server_socket_test.go
index f08e8e9..f1e1983 100644
--- a/lib/go/thrift/server_socket_test.go
+++ b/lib/go/thrift/server_socket_test.go
@@ -41,6 +41,16 @@
 	}
 }
 
+func TestSocketConcurrency(t *testing.T) {
+	host := "127.0.0.1"
+	port := 9090
+	addr := fmt.Sprintf("%s:%d", host, port)
+
+	socket := CreateServerSocket(t, addr)
+	go func() { socket.Listen() }()
+	go func() { socket.Interrupt() }()
+}
+
 func CreateServerSocket(t *testing.T, addr string) *TServerSocket {
 	socket, err := NewTServerSocket(addr)
 	if err != nil {