Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Thread safety #1

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 10 additions & 4 deletions statsd.go
Expand Up @@ -7,13 +7,15 @@ import (
"io"
"math/rand"
"net"
"sync"
"time"
)

// A statsd client representing a connection to a statsd server.
type Client struct {
Name string
rw *bufio.ReadWriter
Name string
rw *bufio.ReadWriter
mutex sync.Mutex
}

func millisecond(d time.Duration) int {
Expand All @@ -39,8 +41,8 @@ func DialTimeout(addr string, timeout time.Duration) (*Client, error) {

func newClient(name string, rw io.ReadWriter) *Client {
return &Client{
name,
bufio.NewReadWriter(bufio.NewReader(rw), bufio.NewWriter(rw)),
Name: name,
rw: bufio.NewReadWriter(bufio.NewReader(rw), bufio.NewWriter(rw)),
}
}

Expand Down Expand Up @@ -82,6 +84,10 @@ func (c *Client) send(stat string, rate float64, format string, args ...interfac
}

format = fmt.Sprintf("%s:%s", stat, format)

c.mutex.Lock()
defer c.mutex.Unlock()

_, err := fmt.Fprintf(c.rw, format, args...)
if err != nil {
return err
Expand Down