Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Thread safety #1

Closed
wants to merge 1 commit into from

2 participants

Tobias Lütke Timothée Peignier
Tobias Lütke

Great client.

I'm using it in an app with many hundreds of goroutines and had to add a mutex to the writing of the socket as it would otherwise interleaf multiple packages and get the server to crash. Otherwise it has been very stable.

Timothée Peignier
Owner

First of all, thanks ! I merged it with a small syntax change, see : f865fc7

It's always a pleasure to have some feedback, I'm glad it works outside of my own use.
If you have any other improvements in mind, don't hesitate.

Timothée Peignier cyberdelia closed this September 08, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Showing 1 unique commit by 1 author.

Sep 07, 2012
Tobias Lütke Made socket writing threadsafe 147d645
This page is out of date. Refresh to see the latest.

Showing 1 changed file with 10 additions and 4 deletions. Show diff stats Hide diff stats

  1. 14  statsd.go
14  statsd.go
@@ -7,13 +7,15 @@ import (
7 7
 	"io"
8 8
 	"math/rand"
9 9
 	"net"
  10
+	"sync"
10 11
 	"time"
11 12
 )
12 13
 
13 14
 // A statsd client representing a connection to a statsd server.
14 15
 type Client struct {
15  
-	Name string
16  
-	rw   *bufio.ReadWriter
  16
+	Name  string
  17
+	rw    *bufio.ReadWriter
  18
+	mutex sync.Mutex
17 19
 }
18 20
 
19 21
 func millisecond(d time.Duration) int {
@@ -39,8 +41,8 @@ func DialTimeout(addr string, timeout time.Duration) (*Client, error) {
39 41
 
40 42
 func newClient(name string, rw io.ReadWriter) *Client {
41 43
 	return &Client{
42  
-		name,
43  
-		bufio.NewReadWriter(bufio.NewReader(rw), bufio.NewWriter(rw)),
  44
+		Name: name,
  45
+		rw:   bufio.NewReadWriter(bufio.NewReader(rw), bufio.NewWriter(rw)),
44 46
 	}
45 47
 }
46 48
 
@@ -82,6 +84,10 @@ func (c *Client) send(stat string, rate float64, format string, args ...interfac
82 84
 	}
83 85
 
84 86
 	format = fmt.Sprintf("%s:%s", stat, format)
  87
+
  88
+	c.mutex.Lock()
  89
+	defer c.mutex.Unlock()
  90
+
85 91
 	_, err := fmt.Fprintf(c.rw, format, args...)
86 92
 	if err != nil {
87 93
 		return err
Commit_comment_tip

Tip: You can add notes to lines in a file. Hover to the left of a line to make a note

Something went wrong with that request. Please try again.