Skip to content

Commit

Permalink
fix data race
Browse files Browse the repository at this point in the history
  • Loading branch information
haya14busa committed Sep 7, 2016
1 parent c315932 commit 0a1eedf
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 8 deletions.
8 changes: 6 additions & 2 deletions vimclient.go
Expand Up @@ -12,6 +12,7 @@ import (
"io"
"math/rand"
"net"
"sync"
"time"
)

Expand Down Expand Up @@ -50,15 +51,18 @@ var _ Handler = &getCliHandler{}
type getCliHandler struct {
handler Handler

connected bool
chCli chan *Client
connected bool
connectedMu sync.RWMutex
chCli chan *Client
}

func (h *getCliHandler) Serve(cli *Client, msg *Message) {
h.connectedMu.Lock()
if !h.connected {
h.chCli <- cli
h.connected = true
}
h.connectedMu.Unlock()
h.handler.Serve(cli, msg)
}

Expand Down
33 changes: 28 additions & 5 deletions vimclient_test.go
Expand Up @@ -9,6 +9,7 @@ import (
"os"
"reflect"
"strings"
"sync"
"testing"
"time"

Expand All @@ -18,16 +19,26 @@ import (
var cli *vim.Client

var defaultServeFunc = func(cli *vim.Client, msg *vim.Message) {}
var serveFunc = defaultServeFunc

var (
serveFunc = defaultServeFunc
serveFunMu sync.RWMutex
)

var vimArgs = []string{"-Nu", "NONE", "-i", "NONE", "-n"}

var waitLog = func() { time.Sleep(1 * time.Millisecond) }

type testHandler struct{}
type testHandler struct {
f func(cli *vim.Client, msg *vim.Message)
}

func (h *testHandler) Serve(cli *vim.Client, msg *vim.Message) {
serveFunc(cli, msg)
fn := h.f
if fn == nil {
fn = defaultServeFunc
}
fn(cli, msg)
}

func TestMain(m *testing.M) {
Expand All @@ -53,23 +64,35 @@ func BenchmarkNewChildClient(b *testing.B) {

func TestNewChildClient(t *testing.T) {
serveFuncCalled := false
var serveFuncCalledMu sync.RWMutex

serveFunMu.Lock()
serveFunc = func(cli *vim.Client, msg *vim.Message) {
// t.Log(msg)
serveFuncCalledMu.Lock()
serveFuncCalled = true
serveFuncCalledMu.Unlock()
}
defer func() { serveFunc = defaultServeFunc }()
defer func() {
serveFunMu.Unlock()
serveFunc = defaultServeFunc
}()

cli, closer, err := vim.NewChildClient(&testHandler{}, vimArgs)
cli, closer, err := vim.NewChildClient(&testHandler{f: serveFunc}, vimArgs)
if err != nil {
t.Fatal(err)
}
defer closer.Close()
if _, err = cli.Expr("1 + 1"); err != nil {
t.Fatal(err)
}

serveFuncCalledMu.Lock()
if !serveFuncCalled {
t.Error("serveFunc must be called")
}
serveFuncCalledMu.Unlock()

status, err := cli.Expr("ch_status(g:vim_go_client_handler)")
if err != nil {
t.Fatal(err)
Expand Down
4 changes: 3 additions & 1 deletion vimserver.go
Expand Up @@ -127,6 +127,8 @@ func connectTmpFile(addr string) (*os.File, error) {
}
defer tmpfile.Close()

connectTemplate.Execute(tmpfile, struct{ Addr string }{addr})
if err := connectTemplate.Execute(tmpfile, struct{ Addr string }{addr}); err != nil {
return nil, err
}
return tmpfile, nil
}

0 comments on commit 0a1eedf

Please sign in to comment.